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.
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.
$variable = mysql_real_escape_string(htmlspecialchars($variable, ENT_QUOTES));
echo "mysql_real_escpe_string does not exist on the server. Upgrade PHP to the latest version.";