有时候我们需要获取客户端的IP去实现一些Web功能,比如天气预报就需要根据访客的IP去算出客户端的地理位置才能显示相应的信息
在PHP中获取客户端的IP非常简单,主要根据$_SERVER['REMOTE_ADDR']
或者$_SERVER['REMOTE_HOST']
这几个变量获取
以下代码是一个获取客户端IP的例子
// 琼台博客 www.qttc.net
function getClientIP() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
使用
// 琼台博客 www.qttc.net
// Get the client IP
$clientIP = getClientIP();
echo $clientIP; // output: 192.168.1.20