Friday, March 27, 2009

Protecting Sql queries from SQL Injection in PHP

SQL injection is a serious concern for webmasters, as an experienced attacker can use this hacking technique to gain access to sensitive data and/or potentially cripple your database. If you haven’t secured your applications, I implore you to get yourself familiar with the following method and grind it into your coding routine. One unsafe query can result in a nightmare for you or your client.
In PHP the easiest way is to pass your data through the mysql_real_escape_string function. By escaping special characters on fields where the user can manipulate the database, you will avoid being vulnerable

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

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

These are two queries which perform same actions. First query is a general query which us used by more users.This query is not more secure when compared for security

The second one same but we used the sprintf method to invoke the query. Here we used mysql_real_escape_string method will will not accept the empty characters or special string. We can use this for the security reasons.

Real time example for this is

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

Here the query is generated as
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

Thus provides a option the query to be executed and This would allow anyone to log in without a valid password.

0 comments:

Post a Comment