2

I was trying to print the superglobal variable $_SERVER['HTTP_X_FORWARDED_FOR'] for testing a proxy blocker for my website. When i open the file, the server returns this error:

Notice: Undefined index: HTTP_X_FORWARDED_FOR in /Applications/XAMPP/xamppfiles/htdocs/test/test.php on line 2

This is what is inside the file:

<?php
echo $_SERVER['HTTP_X_FORWARDED_FOR'];
?>

What's the problem? is that variable not printable? It seems the error that appeard when you do not define a variable.

Thanks in advance.

  • Possible duplicate of http://stackoverflow.com/questions/11452938/how-to-use-http-x-forwarded-for-properly – Naincy Feb 25 '17 at 12:34
  • From [PHP doc](https://secure.php.net/reserved.variables.server): `You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.` – aiko Feb 25 '17 at 12:34

3 Answers3

1

All $_SERVER variables prefixed with HTTP_ represent HTTP headers that you've received from the client.

The only HTTP header that is always present is Host, so ... for everything else, you have to check if it exists first.

Narf
  • 14,600
  • 3
  • 37
  • 66
0

Use

if(array_key_exists("HTTP_X_FORWARDED_FOR", $_SERVER))

To check whether the variable exists before trying to access it

NineBerry
  • 26,306
  • 3
  • 62
  • 93
0

This error will ocurr when the proxy forward isn't done correctly. Could you share more information?

Also I would recommend to use getenv method and check before if var exists (both, the condition and the allocation can be written inside the if statement):

if ($forwarded = getenv('HTTP_X_FORWARDED_FOR')) {
    echo $forwarded;
}

fyi: getenv returns FALSE if the environment var doesn't exist.

Tobbe Widner
  • 106
  • 10