Author Topic: How to stop SQL Injection  (Read 3682 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
How to stop SQL Injection
« on: August 22, 2009, 04:43:59 PM »
To stop SQL Injection you should use:
For numeric/integer values:

$foo = intval($foo);

And for any other data:

$foo = mysql_real_escape_string($foo);

Do never ever trust the user or think "Nah, they won't do or try this". You can also use preg_* functions to filter the input for what it needs to be.
For example if you only want to allow characters from a-z you can do:

$foo = preg_replace('/[^a-z]/i', null, $foo);

Or if you have a select for example, and you want to make sure the submitted value exists in the select, do something like:

$allowed_values = array('foo', 'bar', 'etc');if (!in_array($_POST['select'], $allowed_values)){    // Handle error}