PHP - Shorter Magic Quotes Solution

前端 未结 3 1860
终归单人心
终归单人心 2020-12-22 04:43

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 th

相关标签:
3条回答
  • 2020-12-22 05:29

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

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

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

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

    Array
    (
        [name] => Array
            (
                [got'cha] => O'Reilly
            )
    )
    
    0 讨论(0)
  • 2020-12-22 05:44

    I usually solve that problem this way:

    function smagic($params){
        if(get_magic_quotes_gpc()){
            if(!is_array($params))
                return stripslashes($params);
            else
                return array_combine( array_map('stripslashes',array_keys($params)), array_map('smagic',array_values($params)) );
        }
    }
    

    And then, for $_GET:

    $_GET = smagic($_GET);
    
    0 讨论(0)
  • 2020-12-22 05:46

    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:

    function strip_slashes_recursive(&$value) {
        if (!is_array($value)) {
            $value = strip_slashes($value);
        } else {
            foreach (array_keys($value) as $key) {
                $arrayValue = strip_slashes_recursive($value[$key]);
                unset($value[$key]);
                $value[strip_slashes($key)] = $arrayValue;
            }
        }
    }
    
    foreach (array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST) as &$array) {
        strip_slashes_recursive($array);
    }
    // don't forget to unset references or it can lead to very nasty bugs
    unset($array);
    
    0 讨论(0)
提交回复
热议问题