简体   繁体   中英

X-Forwarded-For causing Undefined index in PHP

I am trying to integrate some third party tracking code into one of my sites, however it is throwing up some errors, and their support isn't being much use, so i want to try and fix their code myself. Most I have fixed, however this function is giving me problems:

private function getXForwardedFor()
{
$s =& $this;

$xff_ips = array();

$headers = $s->getHTTPHeaders();

if ($headers['X-Forwarded-For']) {
$xff_ips[] = $headers['X-Forwarded-For'];
}

if ($_SERVER['REMOTE_ADDR']) {
$xff_ips[] = $_SERVER['REMOTE_ADDR'];
}

return implode(', ', $xff_ips); // will return blank if not on a web server
}

In my dev enviroment where I am showing all errors I am getting:

 Notice: Undefined index: X-Forwarded-For in /sites/webs/includes/OmnitureMeasurement.class.php  on line 1129

Line 1129 is:

if ($headers['X-Forwarded-For']) { 

If I print out $headers I get:

Array
(
[Host] => www.domain.com
[User-Agent] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
[Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[Accept-Language] => en-gb,en;q=0.5
[Accept-Encoding] => gzip,deflate
[Accept-Charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
[Keep-Alive] => 115
[Connection] => keep-alive
[Referer] => http://www10.toptable.com/
[Cookie] => PHPSESSID=nh9jd1ianmr4jon2rr7lo0g553; __utmb=134653559.30.10.1275901644; __utmc=134653559
[Cache-Control] => max-age=0
)

I can't see X-Forwarded-For in there which I think is causing the problem. Is there something I should add to the function to take this into account?

I am using PHP 5.3 and Apache 2 on Fedora

This is not really a big deal, but good to fix nevertheless. It's complaining about you trying to access an array key that doesn't exist. (Even querying the array with that key using if is regarded accessing.)

Change

if ($headers['X-Forwarded-For']) 
  { $xff_ips[] = $headers['X-Forwarded-For']; }

to

if (array_key_exists('X-Forwarded-For', $headers))  
  { $xff_ips[] = $headers['X-Forwarded-For']; }

Even better than array_key_exists is isset because the latter is a language construct (executes faster) and can be used on all sorts of variables. Make it a routine to check that variables you are unsure about are set before trying to read from them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM