

PHP's magic quotes feature is a double edged sword. On the one hand, it is extremely convenient to have the addslashes()
function applied to all incoming data if you are going to be inserting it in to a database. On the other hand, since the
feature can be enabled or disabled in the PHP config file you can often find yourself writing a script without knowing
whether or not magic quotes will be enabled. The script on this page can be used either to ensure all incoming data has had
addslashes() applied to it, or to run stripslashes() if magic quotes are enabled to remove the
slashes from the data.
/* Written by Simon Willison, 16th August 2002. This script is in the public domain. */
/* Recursive helper functions */
function addslashes_recursive($value) {
if (is_array($value)) {
foreach ($value as $index => $val) {
$value[$index] = addslashes_recursive($val);
}
return $value;
} else {
return addslashes($value);
}
}
function stripslashes_recursive($value) {
if (is_array($value)) {
foreach ($value as $index => $val) {
$value[$index] = stripslashes_recursive($val);
}
return $value;
} else {
return stripslashes($value);
}
}
/* Use this if you want addslashes() to be run on all incoming data */
if (!get_magic_quotes_gpc()) {
// Recursively apply addslashes() to all data
$_GET = addslashes_recursive($_GET);
$_POST = addslashes_recursive($_POST);
$_COOKIE = addslashes_recursive($_COOKIE);
$_REQUEST = addslashes_recursive($_REQUEST);
}
/* Use this if you do NOT want addslashes() to be run on all incoming data */
if (get_magic_quotes_gpc()) {
// Recursively apply stripslashes() to all data
$_GET = stripslashes_recursive($_GET);
$_POST = stripslashes_recursive($_POST);
$_COOKIE = stripslashes_recursive($_COOKIE);
$_REQUEST = stripslashes_recursive($_REQUEST);
}
?>
