Sanitize variables to prevent MySQL insertion exploits

When using PHP for web applications, sanitising PHP variables is more important than you might think, even if REGISTER_GLOBALS is OFF!

Basically every script which works with any GET or POST input is affected by this. If not sanitized, this input can easily be abused and manipulated to run so-called MySQL insertion exploits. A successful exploit can be used to download or delete your whole database, grab important passwords from your machine and more.

To prevent insertion exploits, you have to check your FORM input variables for unwanted content. As easy as it sounds, this is all what sanitising variables is about and it will make your PHP scripts more secure in a blink of an eye.

The following example deals with a PHP shopping cart script.
A common line for a shopping cart script would be:

$cart_newitem=$_POST['newitem'];
mysql_query("INSERT INTO `cart` ( ...

The direct MySQL query without verifying your input is very dangerous for the integrity of your site.
The above code can easily be modified to run just about any MySQL query you can imagine on your machine within the rights of your corresponding MySQL user. To sanatize your variables and make sure that your script only inserts valid data and refuses hack attempts, you can use another function.

function sanitize($str){
    $forbidden=array("<", // HTML + logical operator
     ">", // HTML + logical operator
     "'", // SQL string operator
     "\"", // SQL string operator
     "%", // SQL string operator
     "*",  
  
   "´", 
     "`", 
     "="
);
    for ($i=0; $i<count($forbidden); $i++) {
 $repl=$forbidden[$i];
 $str=str_replace("$repl","",$str);
    }
    return ($str);
}

All this does is replace any unwanted characters which could be abused, be it in a simple insertion exploit or something more sophisticated. After replacing all forbidden characters, the clean input is returned.
Now, you may use the sanatising function in your scripts like this:

$cart_newitem=sanitize($_POST['newitem']);

 

Source: (2006-07-26 18:03:45)