Home » MySQL, PHP

Preventing MySQL injection with PHP

12 March 2009 One Comment

A good practice is to check input strings to make sure users don’t put in mySQL commands in your server. For instance, if a username or password POST variable isn’t filtered, there is a potential for an injection like ‘OR myusername=’. In the past, I’ve been using my own PHP toolkit to “clean” the input variables. But recently, I began searching to see if there are a built-in solution in PHP for this, especially since I’m converting a script written in Python that had the filter MySQLdb.escape_string. Enter mysql_real_escape_string()

1) Step 1: Filter out the backtick character, ` which is often used in mySQL to denote field names

$variable = str_replace("`","",$variable);

2) Step 2: If its a username or password field which does not have a space, you should use ctype_alnum This will determine whether there is a character thats not alphanumeric or numeric. So, spaces will not work.

if (ctype_alnum($variable))
{
//allowed variable
}

3) Step 3: Use the mysql_real_escape_string as long as it exists on your server. If it doesn’t exist, an error message will display. I suggest upgrading your PHP if possible since this function will take care of different character sets/etc. You can use this function after the mySQL connection has been initialized.

if(function_exists("mysql_real_escape_string"))
{
$variable = mysql_real_escape_string(htmlspecialchars($variable, ENT_QUOTES));
}
else
{
echo "mysql_real_escpe_string does not exist on the server. Upgrade PHP to the latest version.";
}

One Comment »

  • alaa said:


Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.