PHP-更短的魔术引号解决方案 [英] PHP - Shorter Magic Quotes Solution

查看:89
本文介绍了PHP-更短的魔术引号解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要可移植的应用程序.我知道我应该在PHP配置上禁用魔术引号,但是在这种情况下,我不知道是否可以这样做,所以我在使用以下代码:

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

但是我尝试了,但遇到了我无法理解的错误,例如?name=O'Reilly:

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";}

但是unserialize(stripslashes(serialize($_GET)))给了我这个奇怪的错误:

But unserialize(stripslashes(serialize($_GET))) gives me this weird error:

注意:unserialize():偏移量30 of 32字节错误

由于serialize()中的length属性,我将代码更改为使用JSON函数:

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

但是现在 $_GET数组变为空,有人可以解释一下为什么吗?

However now the $_GET array is coming up empty, can anyone explain me why?

推荐答案

解决了这个问题,我不得不在json_encode()中使用JSON_HEX_APOS标志:

Solved it, I had to use the JSON_HEX_APOS flag in json_encode():

if (get_magic_quotes_gpc() === 1)
{
    $_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
}


在(mqgpc.php?name[got'cha]=O'Reilly)之前:


Before (mqgpc.php?name[got'cha]=O'Reilly):

Array
(
    [name] => Array
        (
            [got\'cha] => O\'Reilly
        )
)

(mqgpc.php?name[got'cha]=O'Reilly)之后:

After (mqgpc.php?name[got'cha]=O'Reilly):

Array
(
    [name] => Array
        (
            [got'cha] => O'Reilly
        )
)

这篇关于PHP-更短的魔术引号解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆