Securing your queries to database from SQL injection with PHP

For escaping dangerous characters in the information you put into queries you can use the following function to check and sanitarize them: 



function quote_smart($value)
{  // Stripslashes
  if (get_magic_quotes_gpc()) {
      $value = stripslashes($value);
  }
  // Quote if not a number or a numeric string
  if ($value instanceof string  || !is_numeric($value)) {
      $value = '"' . mysql_real_escape_string($value) . '"';
  }
  return $value;
}

so your queries look like:

mysql_query("SELECT `id`, `username`, `password` 
FROM `users` 
WHERE `username`= ".quote_smart($username));



 

0 comments: