Monday, September 3, 2012

Escaping User Input to MySQL Database

| 0 comments
In order to protect our websites, we need to make sure that all queries are safe. Beware of all input that usually come from url address or form provided in the pages. We need to escape them before executing the query. Double dashes (--) value can be harmful to the database because in MySQL, it is a command to ignore the next statement in a row. Many other strings can be a threat for your security, so we need to be careful.
PHP provides a function that we can use to escape value before submit query into database. See examples below.

// check whether the PHP support our code
if (function_exists('mysql_real_escape_string') AND is_resource($connection_id))
{
   $str = mysql_real_escape_string($str, $connection_id);
}
elseif (function_exists('mysql_escape_string'))
{
   $str = mysql_escape_string($str);
}
else
{
   $str = addslashes($str);
}


function is_resource used to check whether the given variable is a resource. Here is for an example :

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!is_resource($db_link)) {
   die('Connection error : ' . mysql_error());
}

From the example above, if $db_link is not a resource, it will return false, means the connection failed to establish.

Back to the Topic
mysql_real_escape_string is the best function to use if it is exist, but when the php version doesn't provide that function, we use mysql_escape_string, otherwise we can use addslashes to add back slashes ('\') to the value contains special characters like quotes.

When creating php based application, it is very recommended to use a framework like Code Igniter, Zend or Yii, etc. Because those frameworks can simplify our works, and provide more security to our system. But you must have a knowledge about using PHP as OOP, not only procedural. The first code above is based on the function called escape provided by Code Igniter.


0 comments:

Post a Comment