tags:

views:

134

answers:

2

Hi, 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

+5  A: 

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']; }
Pekka
And goodbye error message. Many thanks for that. (Will accept as soon as it lets me!)
bateman_ap
A: 

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.

Emil Vikström
Woah, why de down-vote? :o
Emil Vikström
There *was* something speaking for array_key_exists over isset when testing arrays but I can't for the life of me remember what it was right now. Still, this is correct, a good point and by no means downvote-worthy. +1
Pekka
@pekka: isset() returns false is the key does exist, but has a null value. array_key_exists does not. However, array_key_exists no longer works on objects anymore as of 5.3
Marc B