Search code examples
phpvariablesbooleanoverwritevariable-variables

PHP variable variable not overriding original variable


I am trying to override some variables in my PHP file using variable variables, but I am getting unexpected results, where the original value is never overwritten, but where the new variable-variable value has a unique value from that of its original variable counterpart.

$case1 = (time() > strtotime('11/22/2020 07:00:00:000AM'));
$case2 = (time() > strtotime('11/16/2020 07:00:00:000AM'));
$case3 = (time() > strtotime('12/01/2020 12:00:00:000PM'));
$case4 = (time() > strtotime('04/24/2021 05:00:00:000AM'));
if (!empty($_GET['schedule_test'])) { $$_GET['schedule_test'] = true; }

If someone someone visits the page path /?schedule_test=case4, the above line should overwrite the variable $case4, because $_GET['schedule_test'] would equal case4 making the statement $$_GET['schedule_test'] = true the equivalent of $case4 = true.

However, even when visiting the URL path /?schedule_test=case4 I still get the value false for $case4. I var_dumped the values for both $case4 and $$_GET['schedule_test'], and their values are different:

echo $case4; // false
echo $$_GET['schedule_test']; // true

The desired goal is to be able to test any of these four cases for any set times with the URL parameter schedule_test being set to any of the variable names (e.g. case1, case2, case3, case4).


Solution

  • PHP documentation says

    In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

    So, you should use

    ${$_GET['schedule_test']}
    

    However, I would strongly advise against using user input directly to decide which variable to write like this. There is a very high risk of allowing attackers to change the internal behaviour of your code.