问题描述
我想获取使用我网站的客户IP地址.我正在使用PHP $_SERVER
超全局变量:
I want to get the client IP address who uses my website. I am using the PHP $_SERVER
superglobal:
$_SERVER['REMOTE_ADDR'];
但是我看到它不能使用此提供正确的IP地址.我得到了我的IP地址,发现它与我的IP地址不同,并且我还可以在某些网站上看到我的IP地址,例如:
But I see it can not give the correct IP address using this. I get my IP address and see it is different from my IP address and I can also see my IP address in some website like:
http://whatismyipaddress.com/
我粘贴了提供我的PHP功能的IP地址,但是此网站未显示任何结果.该问题是怎么发生的?如何获得客户端的IP地址?
I paste the IP address which give my PHP function but this website shows no result about this. How does this problem come about and how can I get IP address of the client?
推荐答案
获取访问者/客户的 IP地址正在使用$_SERVER['REMOTE_ADDR']
或$_SERVER['REMOTE_HOST']
变量.
The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
variables.
但是,有时这不能返回正确的访问者IP地址,因此我们可以使用其他一些服务器变量来获取IP地址.
However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
下面的两个函数等效,只是在如何以及从何处检索值方面有所不同.
The below both functions are equivalent with the difference only in how and from where the values are retrieved.
getenv()用于获取PHP中环境变量的值.
getenv() is used to get the value of an environment variable in PHP.
// Function to get the client IP address
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ _ SERVER是一个数组,其中包含由Web服务器创建的服务器变量.
$_SERVER is an array that contains server variables created by the web server.
// Function to get the client IP address
function get_client_ip() {
$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;
}
这篇关于使用PHP获取客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!