PHP: how to (correctly) remove escaped quotes in arrays when Magic Quotes are ON
Asked Answered
B

2

7

As you know when Magic Quotes are ON, single quotes are escaped in values and also in keys. Most solutions to remove Magic Quotes at runtime only unescape values, not keys. I'm seeking a solution that will unescape keys and values...

I found out on PHP.net this piece of code:

$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);

But I don't like "&" references and arrays as I got bugs like this one in the past...

Is there a "better" way to unescape Magic Quotes (keys and values) at runtime than the one above?

Bullnecked answered 25/1, 2010 at 14:46 Comment(2)
Take a look at the related question on the right side.Lorrainelorrayne
Yeah I did (and even did a Web + SO search before asking question) but I haven't found any solution that work 100% and that don't use "&" references.Bullnecked
E
8

I think this is a little cleaner and avoids reference bugs:

function unMagicQuotify($ar) {
  $fixed = array();
  foreach ($ar as $key=>$val) {
    if (is_array($val)) {
      $fixed[stripslashes($key)] = unMagicQuotify($val);
    } else {
      $fixed[stripslashes($key)] = stripslashes($val);
    }
  }
  return $fixed;
}

$process = array($_GET,$_POST,$_COOKIE,$_REQUEST);
$fixed = array();
foreach ($process as $index=>$glob) {
  $fixed[$index] = unMagicQuotify($glob);
}
list($_GET,$_POST,$_COOKIE,$_REQUEST) = $fixed;
Enmity answered 25/1, 2010 at 15:17 Comment(0)
P
-1
array_walk_recursive($_POST, 'stripslashes');

Do the same for GET and COOKIE.

Pirtle answered 25/1, 2010 at 14:58 Comment(2)
Given that the provided function does strip slashes on the keys as well, might this not completely remove the slashes?Southwester
This won't strip slashes from the keys.Enmity

© 2022 - 2024 — McMap. All rights reserved.