Preventing SQL Injection

For anyone who needs it, here is a script I wrote to prevent SQL injection. It uses references to the original global arrays to clean them up.

  1.  
  2. /**
  3.  * added the following code to enabled readyness for magic_quotes() being removed
  4.  * in PHP6
  5.  *
  6.  * added by C. Cook 15/8/2008
  7.  */
  8. //Turn off magic quotes the manual way, this also cleans up all our nasty data         
  9. $in = array(&$_GET, &$_POST, &$_COOKIE);
  10.                
  11. while (list($k, $v) = each($in)) {
  12.                
  13.         foreach ($v as $key => $val) {
  14.                        
  15.                 if (!is_array($val)) {
  16.                         //now we re-escape our input data
  17.                         $in[$k][$key] = mysql_real_escape_string(stripslashes($val));
  18.                         //$in[$k][$key] = stripslashes($val);                                                                                  
  19.                         continue;
  20.                 }
  21.                 $in[] =& $in[$k][$key];
  22.         }
  23. }
  24. unset($in);     
  25.  
  26.  

Comments are closed.