David Casillas David Casillas - 1 year ago 53
PHP Question

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

(without the
) in the get request, so in the program I have to access it through a variable variable:

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

// ¡¡ This does not work !!
$nombre = "_SERVER";
$var = $$nombre;
// This works
$nombre = "_GET";
$var = $$nombre;

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

Notice: Undefined variable:
in ...

Answer Source

You can try the alternative syntax:

$var = $GLOBALS["_SERVER"];

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download