Magic quotes in PHP Magic quotes in PHP php php

Magic quotes in PHP


Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.

The PHP man page on magic quotes agrees:

"This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed."


Magic quotes were a design error. Their use is incompatible with retainnig your sanity.

I prefer:

if (get_magic_quotes_gpc()) {   throw new Exception("Turn magic quotes off now!");}

Don't write code for compatibility with inherently broken setups. Instead defend aginst their use by having your code FAIL FAST.


I use the following code in the header file of my website to reverse the effects of magic_quotes:

<?php// Strips slashes recursively only up to 3 levels to prevent attackers from// causing a stack overflow error.function stripslashes_array(&$array, $iterations=0) {    if ($iterations < 3) {        foreach ($array as $key => $value) {            if (is_array($value)) {                stripslashes_array($array[$key], $iterations + 1);            } else {                $array[$key] = stripslashes($array[$key]);            }        }    }}if (get_magic_quotes_gpc()) {    stripslashes_array($_GET);    stripslashes_array($_POST);    stripslashes_array($_COOKIE);}?>

Then I can write the rest of my code as if magic_quotes never existed.