Search code examples
phpsuperglobals

Error using $_SERVER in a variable variable (PHP)


I was trying to get the name of a superglobal variable through a GET parameter. I was told to pass only _VAR_NAME (without the $) in the get request, so in the program I have to access it through a variable variable: $$_GET['parameter_name'].

Everything went fine except with $_SERVER. To try what was wrong I just did a small php script to test what was happening. Here is the code:

<?php
    // ¡¡ This does not work !!
        $nombre = "_SERVER";
        $var = $$nombre;
        print_r($var);
    // This works 
        $nombre = "_GET";
        $var = $$nombre;
        print_r($var);
?>

Is there any reason for the _SERVER version not working? I get the following error:

Notice: Undefined variable: _SERVER in ...


Solution

  • You can try the alternative syntax:

    $var = $GLOBALS["_SERVER"];
    print_r($var);
    

    This is functionally equivalent to $$varvar.

    One more critical thing to check is if $_SERVER itself is there. (If not, place an empty count($_SERVER); expression at the start of your script.)

    It can be absent if variables_order= was modified in the php.ini (though it should really just show up as empty array in recent PHP versions.)