如何使用PHP获取客户端IP地址?
我想通过他/她的IP地址登录到我的网站的用户的记录。
如何使用PHP获取客户端IP地址?
我想通过他/她的IP地址登录到我的网站的用户的记录。
当前回答
无论您做什么,请确保不要信任从客户端发送的数据。$_SERVER['REMOTE_ADDR']包含连接方的真实IP地址。这是你能找到的最可靠的值。
然而,它们可能在代理服务器的后面,在这种情况下,代理可能已经设置了$_SERVER['HTTP_X_FORWARDED_FOR'],但这个值很容易被欺骗。例如,它可以由没有代理的人设置,或者IP可以是来自代理后面LAN的内部IP。
这意味着如果您要保存$_SERVER['HTTP_X_FORWARDED_FOR'],请确保您也保存$_SERVER['REMOTE_ADDR']值。例如,将两个值保存在数据库的不同字段中。
如果要将IP保存为字符串到数据库,请确保至少有45个字符的空间。IPv6将继续存在,这些地址比旧的IPv4地址更大。
(请注意,IPv6通常最多使用39个字符,但IPv4地址也有一个特殊的IPv6符号,其完整形式最多可达45个字符。所以如果你知道你在做什么,你可以使用39个字符,但如果你只是想设置并忘记它,请使用45)。
其他回答
在PHP中,获取公共IP的最后一个选项应该始终是$_SERVER["REMOTE_ADDR"],因为有太多的安全原因。
下面是获取客户端已验证的IP地址的变通方法。
public static function getPublicIP() : string
{
$realIP = "Invalid IP Address";
$activeHeaders = [];
$headers = [
"HTTP_CLIENT_IP",
"HTTP_PRAGMA",
"HTTP_XONNECTION",
"HTTP_CACHE_INFO",
"HTTP_XPROXY",
"HTTP_PROXY",
"HTTP_PROXY_CONNECTION",
"HTTP_VIA",
"HTTP_X_COMING_FROM",
"HTTP_COMING_FROM",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"ZHTTP_CACHE_CONTROL",
"REMOTE_ADDR" #this should be the last option
];
#Find active headers
foreach ($headers as $key)
{
if (array_key_exists($key, $_SERVER))
{
$activeHeaders[$key] = $_SERVER[$key];
}
}
#Reemove remote address since we got more options to choose from
if(count($activeHeaders) > 1)
{
unset($activeHeaders["REMOTE_ADDR"]);
}
#Pick a random item now that we have a secure way.
$realIP = $activeHeaders[array_rand($activeHeaders)];
#Validate the public IP
if (filter_var($realIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
{
return $realIP;
}
return $realIP;
}
正如您在这里看到的,$_SERVER["REMOTE_ADDR"]是IP的最后一个选项。在收到IP后,我们也验证IP,以确保质量和安全。
我最喜欢的解决方案是Zend Framework 2使用的方式。它还考虑$_SERVER属性HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, REMOTE_ADDR,但是它声明了一个类来设置一些可信代理,并且它返回一个IP地址而不是一个数组。我认为这是最接近它的解决方案:
class RemoteAddress
{
/**
* Whether to use proxy addresses or not.
*
* As default this setting is disabled - IP address is mostly needed to increase
* security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
* just for more flexibility, but if user uses proxy to connect to trusted services
* it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
*
* @var bool
*/
protected $useProxy = false;
/**
* List of trusted proxy IP addresses
*
* @var array
*/
protected $trustedProxies = array();
/**
* HTTP header to introspect for proxies
*
* @var string
*/
protected $proxyHeader = 'HTTP_X_FORWARDED_FOR';
// [...]
/**
* Returns client IP address.
*
* @return string IP address.
*/
public function getIpAddress()
{
$ip = $this->getIpAddressFromProxy();
if ($ip) {
return $ip;
}
// direct IP address
if (isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}
return '';
}
/**
* Attempt to get the IP address for a proxied client
*
* @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
* @return false|string
*/
protected function getIpAddressFromProxy()
{
if (!$this->useProxy
|| (isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies))
) {
return false;
}
$header = $this->proxyHeader;
if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
return false;
}
// Extract IPs
$ips = explode(',', $_SERVER[$header]);
// trim, so we can compare against trusted proxies properly
$ips = array_map('trim', $ips);
// remove trusted proxy IPs
$ips = array_diff($ips, $this->trustedProxies);
// Any left?
if (empty($ips)) {
return false;
}
// Since we've removed any known, trusted proxy servers, the right-most
// address represents the first IP we do not know about -- i.e., we do
// not know if it is a proxy server, or a client. As such, we treat it
// as the originating IP.
// @see http://en.wikipedia.org/wiki/X-Forwarded-For
$ip = array_pop($ips);
return $ip;
}
// [...]
}
在这里查看完整代码: https://raw.githubusercontent.com/zendframework/zend-http/master/src/PhpEnvironment/RemoteAddress.php
这个函数很紧凑,可以在任何地方使用。但是!
别忘了这一点!在这类函数或代码块中,不能保证记录用户的真实IP地址,因为有些用户可以使用代理或其他安全网关来实现不可见或无法跟踪
PHP函数:
function GetIP()
{
if ( getenv("HTTP_CLIENT_IP") ) {
$ip = getenv("HTTP_CLIENT_IP");
} elseif ( getenv("HTTP_X_FORWARDED_FOR") ) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
if ( strstr($ip, ',') ) {
$tmp = explode(',', $ip);
$ip = trim($tmp[0]);
}
} else {
$ip = getenv("REMOTE_ADDR");
}
return $ip;
}
用法:
$IP = GetIP();或直接GetIP();
这里有一个简单的一行代码
$ip = $_SERVER['HTTP_X_FORWARDED_FOR']?: $_SERVER['HTTP_CLIENT_IP']?: $_SERVER['REMOTE_ADDR'];
编辑:
上面的代码可能会返回保留地址(如10.0.0.1),所有代理服务器的地址列表,等等。 要处理这些情况,请使用以下代码:
function valid_ip($ip) {
// for list of reserved IP addresses, see https://en.wikipedia.org/wiki/Reserved_IP_addresses
return $ip && substr($ip, 0, 4) != '127.' && substr($ip, 0, 4) != '127.' && substr($ip, 0, 3) != '10.' && substr($ip, 0, 2) != '0.' ? $ip : false;
}
function get_client_ip() {
// using explode to get only client ip from list of forwarders. see https://en.wikipedia.org/wiki/X-Forwarded-For
return
@$_SERVER['HTTP_X_FORWARDED_FOR'] ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2)[0] :
@$_SERVER['HTTP_CLIENT_IP'] ? explode(',', $_SERVER['HTTP_CLIENT_IP'], 2)[0] :
valid_ip(@$_SERVER['REMOTE_ADDR']) ?:
'UNKNOWN';
}
echo get_client_ip();
它应该包含在$_SERVER['REMOTE_ADDR']变量中。