Check Slash on Database Input

If you are querying a database you should get into the habit of sanitising your input, even if it's not coming from users at the moment it might do in the future. SQL injection attacks are all too common and they can be easily prevented.

The addslashes() function takes a string as the input and returns a string with backslashes before all characters that required quoting in database queries. The characters it acts on are quote, double quote, backslash and NUL (or a NULL byte). Magic quotes runs addslashes() on all COOKIE, GET and POST data. The important thing is not to use addslashes() and magic quotes on the same string as everything will be double escaped.

Use the get_magic_quotes_gpc() function to see if magic quotes is enabled. If it isn't then use the PHP function addslashes() to do the same thing. Use this function if you have any user input in order to sanitise anything that you are about to send to a database.

The following function will add slashes to the string even if magic quotes is disabled.

private static function checkslash($slashes_string)
{
  if (get_magic_quotes_gpc()==1) {
    return $slashes_string;
  } else {
    return addslashes($slashes_string);
  };
}

You should never rely on magic_quotes being enabled on any server. So get into the habit of doing this on your SQL strings.

$sql = 'SELECT * FROM table WHERE table.name="'.checkslash($string).'"';

This has the effect of escaping all characters in the string that might cause error or security breaches.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
7 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.