X-Forwarded-用于在PHP中导致未定义的索引

时间:2010-06-07 13:17:05

标签: php apache

我正在尝试将一些第三方跟踪代码集成到我的某个网站中,但它会抛出一些错误,并且它们的支持没有多大用处,所以我想尝试自己修复代码。大多数我已经修复,但是这个功能给了我一些问题:

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
}

在我的开发环境中,我正在展示我遇到的所有错误:

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

第1129行是:

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

如果我打印出$ header,我会得到:

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
)

我认为X-Forwarded-For在那里我认为是导致问题的。我是否应该在函数中添加一些内容来考虑这一点?

我在Fedora上使用PHP 5.3和Apache 2

2 个答案:

答案 0 :(得分:6)

这不是什么大不了的事,但不过很好。它抱怨你试图访问不存在的数组键。 (即使使用if使用该密钥查询数组也被视为访问。)

更改

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

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

答案 1 :(得分:0)

甚至比array_key_exists更好isset因为后者是一种语言结构(执行得更快),并且可以用于各种变量。在尝试从中读取变量之前,请确保设置您不确定的变量。

相关问题