Why cant I access $_POST variable with a hyphen/dash in its key if passing key as variable?

前端 未结 2 1877
小鲜肉
小鲜肉 2021-01-25 00:40

I\'ve written a small static method for my class which returns either $_POST variable if it is set or NULL otherwise. Input elements in HTML form have

2条回答
  •  死守一世寂寞
    2021-01-25 01:27

    So the problem was, that casting object to an array adds null characters to array keys. They are not just class name+property name. It's how PHP manages private class properties when casting.

    $object = new Customer();
    $arr = (array)$object;
    print_r(array_map("addslashes", array_keys($arr)));
    

    Outputs:

    Array ( 
            [0] => \0Customer\0test1 
            [1] => \0Customer\0test2
          )
    

    Im not sure why var_dump() doesnt show those null bytes. Might be my next question I guess. So those nulls were still there in my static method argument. But why PHP stops right after dash/hyphen?

    In PHP we can simply write:

    $Tmp= 'hehe';
    

    But for the same in C, we would use the following code:

    Char Tmp [4];
    Tmp [0] = 'h';
    Tmp [1] = 'e';
    Tmp [2] = 'h';
    Tmp [3] = 'e';
    Tmp [4] = '\0';
    

    C handles strings as a character array, it needs a way to define the last character of the string. This is done using a null byte. A null byte is donated by \0 in C. So when the program runs, it starts reading the string from the first character until the null byte is reached. This creates a problem. As we know, PHP is also implemented in C. This can become an issue, because some functions in PHP might handle an input string as they are handled by C.

    Sources: #71673, null-byte-injection-php

    EDIT 1: Solution added

    Solution is to replace '\0' characters as well as class name with "" in my foreach loop:

    foreach($arr as $key => $val) {
        $newKey = str_replace(array(get_class($object), "\0"), "", $key);
        $newArr[$newKey] = getPost(strtolower(get_class($object))."-".$newKey);
    }
    

提交回复
热议问题