How to prevent MySQL injection

Protect your website from hackers that use MySQL code injections to gain access to your database, compromising your confidential data.

Check for magic quotes in your server and process it for http requests:

if (!get_magic_quotes_gpc()) {
$_GET = array_map(‘trim’, $_GET);
$_GET = array_map(‘addslashes’, $_GET);
$_POST = array_map(‘trim’, $_POST);
$_POST = array_map(‘addslashes’, $_POST);
$_COOKIE = array_map(‘trim’, $_COOKIE);
$_COOKIE = array_map(‘addslashes’, $_COOKIE);
$_REQUEST = array_map(‘trim’, $_REQUEST);
$_REQUEST = array_map(‘addslashes’, $_REQUEST);
}

Sanitize user inputs:

function cleanQuery($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
if (phpversion() >= ‘4.3.0’) {
$string = mysql_real_escape_string(htmlentities($string, ENT_QUOTES));
}
else {
$string = mysql_escape_string(htmlentities($string, ENT_QUOTES));
}
return $string;
}

Just include this into your common configuration file. You can put this into your site into action like in this example, which only takes a few modification:

Original:

$var1 = $_GET["var1"];
$var2 = $_POST["var2"];
$var3 = $_REQUEST["var3"];

Modified:

$var1 = cleanQuery($_GET["var1"]);
$var2 = cleanQuery($_POST["var2"]);
$var3 = cleanQuery($_REQUEST["var3"]);

If you have a more secure form of Anti-SQL injection, please share it!

Leave a Reply

Your email address will not be published. Required fields are marked *