Check Slash on Database Input

10th January 2008

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.

  1. private static function checkslash($slashes_string)
  2. {
  3. return $slashes_string;
  4. } else {
  5. return addslashes($slashes_string);
  6. };
  7. }

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.