Wednesday, October 11, 2006

SQL Injection in PHP

Here are 2 useful function when dealing with php / mysql system and want to avoid sql injection.

function m_str($arr) {
   $return_array = array();
   if (get_magic_quotes_gpc()) $strip = true;
   else $strip = false;
   foreach($arr as $key => $val) {
     if ($strip) $val = stripslashes($val);
     $return_array[$key] = "'" . mysql_real_escape_string($val) . "'";
   }
   return $return_array;
}

function m_num($arr,$defaultvalue = 0) {
   $return_array = array();
   if (get_magic_quotes_gpc()) $strip = true;
   else $strip = false;
   foreach($arr as $key => $val) {
     if ($strip) $val = stripslashes($val);
     $return_array[$key] = ((is_numeric($val)) ? $val : $defaultvalue);
   }
   return $return_array;
}



After adding there function to an included function file of your site, you can do something like :


$_POSTS = m_str($_POST);
$_GETS = m_str($_GET);
$_POSTN = m_num($_POST);
$_GETN = m_num($_GET);


And anytime you need to use the POST or GET collection as a string in a mysql query, use $_POSTS['field'] or $_GETS['field'].

If you need a numeric value in your query, you can use $_POSTN['field'] or $_GETN['field'] and be sure to have a numeric value in it.

I have also added a parameter for the m_num function to be able to set the value of the field when a non-numeric value is in it.

your mysql query should look like this :


$result = mysql_query("SELECT (fieldlist...) FROM (tablename) WHERE string=".$_POSTS['field']." AND numeric=".$_POSTN['field'],$link);

Where $link is your mysql connection.


Note: You need to have a valid mysql connection established before using the m_str function as the function mysql_real_escape_string() encode strings from an internal mysql server function.

No comments: