Methods for removing magic quotes

If magic quotes are on and can’t be disabled, the PHP manual suggests using this to undo the damage:


<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

However, if you are just working with a simple form-to-email script, is there any disadvantage to simply using something like this to remove the slashes?


if ( get_magic_quotes_gpc() ) { 
  $name = stripslashes($name);
  $email = stripslashes($email);
  $message = stripslashes($message);
}

Hi Ralph,

Like you say

However, if you are just working with a simple form-to-email script, is there any disadvantage to simply using something like this to remove the slashes?
there is no disadvantage to using your approach.

Regards,
Steve

Cool, thanks ServerStorm. Do you think that simpler code is a bit inefficient? I don’t know PHP well enough yet to know if if can be simplified.

It is as efficient as it gets, it has no loop. But it is more efficient for you to type out every single variable that you are going to use? That is a different question.

Indeed. There’s no doubt a tipping point beyond which it’s a silly route to take.

Could do this:


if ( get_magic_quotes_gpc() )
  array_walk_recursive( $_GET, function ( &$v ) { $v = stripslashes( $v ); } );

If you really wanted to do large sets…

Thanks logic_earth. I’ll play around with that. :slight_smile: