Monday, July 26, 2010

Use mysql_real_escape_string() function to avoid mysql injections

// 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'] = 'admin';
$_POST['password'] = "' OR ''='";
// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL as:

SELECT * FROM users WHERE user='admin' AND password='' OR ''=''

This would allow anyone to log in without a valid password.


Solution:
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($_POST['user']),
mysql_real_escape_string($_POST['password']));
?>
Here mysql_real_escape_string function prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a to make data safe before sending a query to MySQL. So user can't hack your database.

0 comments: