Jaslabs: High performance Software

High Performance Software

Archive for the 'php' Category

A better way to Protect Your PHP/MySQL Queries from SQL Injection

By Justin Silverton

In a recent article I saw today about php/mysql security, called “protecting your php/mysql queries from sql injection”, The following method was described as a safe way to execute mysql queries (preventing what is known as a sql injection attack).

// This is a vulnerable query.
$query = "SELECT * FROM products WHERE name='$productname'";
mysql_query($query);

// This just uses mysql_escape_string
$query = sprintf("SELECT * FROM products WHERE name='%s'",
mysql_real_escape_string($productname));
mysql_query($query);

This will work, with select and insert statements, but will not work with statements such as: LIKE, GRANT, or REVOKE. This is a more secure way of preventing SQL injection attacks.


// This query is more secure
$query = sprintf("SELECT * FROM products WHERE name='%s'",
addcslashes(mysql_real_escape_string($productname),'%_'));
mysql_query($query);

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
7 comments

How to create a self extracting PHP script

By Justin Silverton

PHP has a built-in command called __HALT_COMPILER__. This command Halts the execution of the compiler. This can be useful to embed data in PHP scripts. Below is an example of a self-extracting php script. When executed, a second php file will be extracted in the same directory called testscript1.php.

<?php

//gzdecode function
function gzdecode ($data) {
$flags = ord(substr($data, 3, 1));
$headerlen = 10;
$extralen = 0;
$filenamelen = 0;
if ($flags & 4) {
$extralen = unpack('v' ,substr($data, 10, 2));
$extralen = $extralen[1];
$headerlen += 2 + $extralen;
}
if ($flags & 8  ) // Filename
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 16) // Comment
$headerlen = strpos($data, chr(0), $headerlen) + 1;
if ($flags & 2) // CRC at end of file
$headerlen += 2;
$unpacked = gzinflate(substr($data, $headerlen));
if ($unpacked === FALSE)
$unpacked = $data;
return $unpacked;
}

$fp = fopen(__FILE__, 'r');
// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);
// and output it
$buffer = fread($fp,8192);
$decoded = gzdecode(base64_decode($buffer));
//$uncompressed = gzdecode($decoded);

$filename = "testscript1.php";
$fd = fopen($filename,"w");
fwrite($fd,$decoded);
fclose($fd);

__halt_compiler();H4sICKE9CEcAC3Rlc3RmaWxlMS5waHAAs
7EvyCjg5eLlSk3OyFdQKsnILFYAopLU4hKFtMycVAVDJWteLns7AKhVcUooAAAA

How it works

The file that is extracted is gzipped, base64 encoded, and stored at the end of the the file (right after the __halt_compiler directive). The script uses a custom function called gzdecode to gunzip the file, it is then base64 decoded and written to a file. This is just a simple example to show what is possible with PHP. A more advanced version could use a function to tar and gzip a file so multiple files can be extracted.

The code example from this article can be download here

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
5 comments

PHP library for Microsoft AJAX

By Justin Silverton

Microsoft has released their AJAX library package for non-windows systems which contains a complete set of client JavaScript components that are included in the full ASP.NET AJAX installation. Developers over at Codeplex have developed a library that allows you to integrate your PHP applications with this package.

requirements

  • PHP 5.2 — 5.2 is required for json_encode/json_decode; For earlier versions, you will need to install php-json

How to install

  1. Download the PHP library from codeplex here
  2. Download the Microsoft AJAX Library here
  3. After extracting both of these, place all the files from the Microsoft Ajax library in a directory called “MicrosoftAjaxLibrary”

Example

The following is a simple example that demonstrates a simple ajax transmission using the microsoft libraries.

(hello.htm)

<html>
<head>
<title>Hello, World!</title>
<script type="text/javascript" src="../../MicrosoftAjaxLibrary/MicrosoftAjax.js"></script>
<script type="text/javascript" src="HelloService.php/js"></script>
</head>
<body>
Name: <input id="name" type="text" /> <input type="button" value="Say Hello" onclick="button_click(); return false;" />
<br />
Response from server: <span id="response"></span>
</body>
<script type="text/javascript">
function button_click() {
HelloService.SayHello($get('name').value, function (result) { $get('response').innerHTML = result; });
}
</script>
</html>

(HelloService.php)

<?php

require_once '../../dist/MSAjaxService.php';

class HelloService extends MSAjaxService
{
function SayHello($name)
{
return "Hello, " . $name . "!";
}
}

$h = new HelloService();
$h->ProcessRequest();

?>

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
1 comment

Using Ajax across multiple domains

By Justin Silverton

XMLHttpRequest, the main component behind AJAX, does not automatically work across multiple domains. This means that you cannot make a request to an ovject on a domain that is different from the web page’s domain. There is an easy solution to this issue: apache’s mod_rewrite module.

Example

function getXMLHttpObject()
{
if (window.XMLHTTPRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
else
return null;
}

function handleHTTPResponse()
{
if (http.readyState == 4) {
results = http.responseText;
}
}

var http = getXMLHttpObject();

http.open("POST"."http://www.yahoo.com/service");
http.onreadystatechange = handleHttpResponse;

The above example will fail with both Firefox and Internet Explorer (unless you are running it on a web page located on the yahoo domain). There are other ways to allow cross site ajax. Within Internet Exporer, the default security settings can be changed or a host can be added to the “trusted hosts” list. Firefox, on the other hand, has a concept called signed scripts. Both of these methods will not work for most websites on the Internet. This is because it would involve every user coming to your site adding your page to their trusted host list.

Apache setup

  1. Install apache with both mod_rewrite and proxy enabled.
  2. Create the following rule: RewriteRule ^/yahoo_proxy http://www.yahoo.com/service [P]

Note: The [P] indicates a pass-through proxy.

Replace the above line: (http.open("POST"."http://www.yahoo.com/service")) with

http.open("POST"."http://your_host/yahoo_proxy") and a connection will be made to the yahoo domains through your apache server while not violating the security restrictions of IE or Firefox.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
1 comment

A PHP compatible MD5 function in c#

By Justin Silverton

The following is a function written in c# that will return a PHP compatible MD5 hash of a file, given the name. The equivalent function in PHP is md5_file().


public string MD5Hash( string sFilePath )
{
try
{
MD5CryptoServiceProvider md5Provider
= new MD5CryptoServiceProvider();
FileStream fs
= new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
Byte[] hashCode
= md5Provider.ComputeHash(fs);

string ret = "";

foreach (byte a in hashCode)
{
if (a<16)
ret += "0" + a.ToString ("x");
else
ret += a.ToString ("x");
}

fs.Close();
return ret;
}
catch( Exception ex )
{
throw ex;
}
}

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • DZone
  • Slashdot
  • StumbleUpon
  • Technorati
3 comments

Next Page »