I'm writing a app that needs to be portable. I know I should disable magic quotes on the PHP configuration but in this case I don't know if I can do that, so I'm using the following code:
if (get_magic_quotes_gpc() === 1)
{
$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);
}
To simplify the process of disabling magic quotes I had the following idea:
if (get_magic_quotes_gpc() === 1)
{
foreach (array('GET', 'POST', 'COOKIE', 'REQUEST') as $array)
{
${'_'.$array} = unserialize(stripslashes(serialize(${'_'.$array})));
}
}
But I tried and I got an error I'm unable to understand, for instance with ?name=O'Reilly
:
serialize($_GET); // a:1:{s:4:"name";s:9:"O\'Reilly";}
stripslashes(serialize($_GET)); // a:1:{s:4:"name";s:9:"O'Reilly";}
But unserialize(stripslashes(serialize($_GET)))
gives me this weird error:
Notice: unserialize(): Error at offset 30 of 32 bytes
EDIT: Due to the length attribute in serialize()
I changed the code to use JSON functions:
if (get_magic_quotes_gpc() === 1)
{
foreach (array('GET', 'POST', 'COOKIE', 'REQUEST') as $array)
{
${'_' . $array} = json_decode(stripslashes(json_encode(${'_' . $array})), true);
}
}
However now the $_GET
array is coming up empty, can anyone explain me why?
I don't think the second version will work. Serialized strings are stored along with their length, if you are removing characters, you would need to update that length value. I would rather implement it this way to improve readability:
I usually solve that problem this way:
And then, for $_GET:
Solved it, I had to use the
JSON_HEX_APOS
flag injson_encode()
:Before (
mqgpc.php?name[got'cha]=O'Reilly
):After (
mqgpc.php?name[got'cha]=O'Reilly
):