繁体   English   中英

X-Forwarded-For在PHP中导致未定义索引

[英]X-Forwarded-For causing Undefined index in PHP

我正在尝试将一些第三方跟踪代码集成到我的一个站点中,但是它抛出了一些错误,并且对他们的支持使用不多,所以我想尝试自己修复它们的代码。 大多数问题我都已解决,但是此功能给我带来了问题:

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

这并不是什么大不了的事情,但是仍然可以解决。 它抱怨您试图访问不存在的阵列键。 (即使使用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']; }

isset比array_key_exists更好,因为后者是一种语言构造(执行速度更快),并且可以用于各种变量。 使其成为例行程序,然后再尝试从中读取不确定的变量,并检查是否已确定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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