SQL Injection — How to sanitize your user forms.

SQL injection… I hate this. I’ve been a victim of this once and it caused me a lot of work… (not too much, I just restored the database from the previous day). Anyway, since then I always use my general input ‘cleaning’ routine where all data that come from forms are “cleaned” and sanitized.

In ASP, I replace all single quote marks with null, and also scan the string for “Hot Words” and remove them, or kill the program.

Here’s my new PHP equivalent.

// Description: Use this to clean user input
function CleanInput($str) {
 // if $strHotWords detected, die()
 $strHotWords = "CAST(|<IFRAME|<SCRIPT";
 $strHotWords = explode("|",$strHotWords);
 for($i=0;$i<count($strHotWords);$i++) {        
 if (strpos(strtolower($str),strtolower($strHotWords[$i])) !== false) {
    $str = '';    // blank it
    die ('');    // don't display any clue to hackers
 } // end if
 } // for

 // replace bad characters
 //$bad  = array("'","-","=",'"','%','='," ");
 //$good = array ("","","","","","","");
 //$str  = str_replace($bad,$good,$str);

 // for good measure, escape string
 return mysql_real_escape_string($str);
} // function

Uncomment the code after //replace bad characters if you want to be AGGRESSIVE in cleaning your input strings.

All quote, dash, equal, single quote, and spaces are replaced with empty strings. Now, there’s absolutely no way any valid SQL Injection could be created!

This entry was posted in Uncategorized. Bookmark the permalink.