1

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.

  • 1
    Terrible idea to use eval for something like this in the first place. https://stackoverflow.com/questions/9628176/using-a-string-path-to-set-nested-array-data – CBroe Jul 14 '21 at 11:46
  • Do you have PHP error reporting turned all the way on? – Chris Haas Jul 14 '21 at 11:46
  • _“And the result is nothing.”_ - apart from the syntax error (enable proper PHP error reporting!) – well, what would be the result you expected from `$_COOKIE['key1']['key2']['key3']` _on its own_? If you had written _just that_ onto a line into a PHP file directly, it would not produce any output or any return value either. – CBroe Jul 14 '21 at 11:51
  • @ChrisHaas I got this error : Parse error: syntax error, unexpected end of file in /hdd/program/web/demo91/modul/admin/config.php(31) : eval()'d code on line 1 – Fauzan Samsuri Jul 14 '21 at 12:17

2 Answers2

0

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'));
User863
  • 19,346
  • 2
  • 17
  • 41
  • I like your code so much, so elegant and efficient. But how using this way to set value to array cookie? thanks in advance. – Fauzan Samsuri Jul 14 '21 at 12:39
  • @FauzanSamsuri what you are asking is something irrelevant to this question. Don't forget to [accept the answer](https://stackoverflow.com/help/accepted-answer) if it really helped – User863 Jul 14 '21 at 12:47
0

Problem solved.

I change

return eval($t); 

to

return eval('echo ' . $t . ';');

and now it works as expected.