您好,欢迎访问一九零五行业门户网

PHP如何获取客户端的IP地址?(代码示例)

本篇文章给大家带来的内容是介绍php如何获取客户端的ip地址?(代码示例),让大家了解php获取ip地址的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。
首先我们来了解相关变量的含义:
$_server['remote_addr']:浏览当前页面的用户计算机的ip地址
$_server['http_client_ip']:客户端的ip
$_server['http_x_forwarded_for']:浏览当前页面的用户计算机的网关
$_server['http_x_real_ip']:nginx 代理模式下,获取客户端真实ip
下面我们通过简单的代码示例来介绍php获取客户端ip地址的方法。
/** *  获取客户端ip地址 */function real_ip(){    $ip = $_server['remote_addr'];    if (isset($_server['http_x_forwarded_for']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_server['http_x_forwarded_for'], $matches)) {        foreach ($matches[0] as $xip) {            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {                $ip = $xip;                break;            }        }    } elseif (isset($_server['http_client_ip']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_server['http_client_ip'])) {        $ip = $_server['http_client_ip'];    } elseif (isset($_server['http_cf_connecting_ip']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_server['http_cf_connecting_ip'])) {        $ip = $_server['http_cf_connecting_ip'];    } elseif (isset($_server['http_x_real_ip']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_server['http_x_real_ip'])) {        $ip = $_server['http_x_real_ip'];    }    return $ip;}
总结:以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。
以上就是php如何获取客户端的ip地址?(代码示例)的详细内容。
其它类似信息

推荐信息