Disable “magic quotes” in PHP

“Magic quotes” is the name for a mechanism in PHP, which adds a leading backslash (\) for quotes and double quotes into variables, which come from “outside” into a script (URL parameters, database fields, text files and so on).

Example:

"Hello world" becomes to \"Hello world\"
and 'another word' becomes to \'another word\'

Generally this mechanism is more annoying than useful, because you have to use stripslashes() for those variables, before you can use them – and you still need to check, if this is neccessary at all and you must not use this function, if magic quotes are not enabled.

To avoid potential security problems, like SQL injection, you should use other techniques anyway, like e.g. prepared statements.

Code snippet to avoid magic quotes during runtime

To change the magic quotes behaviour, you have to modify the correspondent setting in the PHP configuration (php.ini). If this is not possible, you can use the following code snippet at the beginning of a script to achieve the same result:

disable_magicquotes.php
<?php
ini_set('magic_quotes_runtime', 0);
 
if(get_magic_quotes_gpc())
{
  $superglobals=array(
    "_REQUEST",
    "_GET",
    "_POST",
    "_COOKIE",
    "_ENV",
    "_SERVER");
 
  foreach($superglobals as $globalname)
  {
    foreach($GLOBALS[$globalname] as $name => $value)
    {
      if(!is_array($value))
      {
        $GLOBALS[$globalname][$name] = stripslashes($value);
      }
    }
  }
 
  unset($superglobals);
}
?>

The easiest way is it, to save this snippet in a separate file and to include() this file in all affected scripts, if needed.