学习积累

php获取IP地址

    今天给出一个比较完善的获取IP地址的算法,作为一个记录:

/**

* 获取客户端IP
* @return string $ipaddress 客户端IP
*/
public static function IP()
{
$ip = ”;
if (isset($_SERVER[‘HTTP_CLIENT_IP’]) && $_SERVER[‘HTTP_CLIENT_IP’]) {
$ip = $_SERVER[‘HTTP_CLIENT_IP’];
} elseif (isset($_SERVER[‘HTTP_X_FORWARDED_FOR’]) && $_SERVER[‘HTTP_X_FORWARDED_FOR’]) {
$ip = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
$ip = explode(‘,’, $ip);
$ip = trim($ip[0]);
} elseif (isset($_SERVER[‘HTTP_X_FORWARDED’]) && $_SERVER[‘HTTP_X_FORWARDED’]) {
$ip = $_SERVER[‘HTTP_X_FORWARDED’];
} elseif (isset($_SERVER[‘HTTP_FORWARDED_FOR’]) && $_SERVER[‘HTTP_FORWARDED_FOR’]) {
$ip = $_SERVER[‘HTTP_FORWARDED_FOR’];
} elseif (isset($_SERVER[‘HTTP_FORWARDED’]) && $_SERVER[‘HTTP_FORWARDED’]) {
$ip = $_SERVER[‘HTTP_FORWARDED’];
} elseif (isset($_SERVER[‘REMOTE_ADDR’]) && $_SERVER[‘REMOTE_ADDR’]) {
$ip = $_SERVER[‘REMOTE_ADDR’];
} else {
$ip = ”;
}
return $ip;
}
Be the First to comment.

Leave a Comment