Search code examples
phpcookieseval

PHP: get value from array variable (which is a string) using eval() not working


I have a function like this:

function getvar() { 
  $n = func_num_args(); 
  $l = func_get_args(); 
  $t = '$_COOKIE';
  for ($i = 0; $i < $n; $i++) { 
    $t .= "['".$l[$i]."']"; 
  }
  // $t would be like $_COOKIE['arg1']['arg2']['arg3']
  return eval($t); 
}

I also have cookie expired in 24 hours:

$_COOKIE['key1']['key2']['key3'] = 'TEST';

Then I call getvar() using:

$test = getvar('key1', 'key2', 'key3');
echo $test; //result should be 'TEST'

And the result is nothing.


Solution

  • Using array_reduce()

    $_COOKIE = ['key1' => [ 'key2' => [ 'key3' => 'TEST' ]]];
    
    function getvar(...$args)
    {
        return array_reduce($args, fn ($a, $k) => $a[$k], $_COOKIE);
    }
    
    print_r(getvar('key1', 'key2', 'key3'));