PHP获取真实IP地址

 1 <?php
 2 
 3 function get_client_ipaddress($type = 0)
 4 {
 5     $type = $type ? 1 : 0;
 6     static $ip = NULL;
 7     if ($ip !== NULL)
 8         return $ip[$type];
 9     if ($_SERVER['HTTP_X_REAL_IP']) { //nginx 代理模式下,获取客户端真实IP
10         $ip = $_SERVER['HTTP_X_REAL_IP'];
11     } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { //客户端的ip
12         $ip = $_SERVER['HTTP_CLIENT_IP'];
13     } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { //浏览当前页面的用户计算机的网关
14         $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
15         $pos = array_search('unknown', $arr);
16         if (false !== $pos)
17             unset($arr[$pos]);
18         $ip = trim($arr[0]);
19     } elseif (isset($_SERVER['REMOTE_ADDR'])) {
20         $ip = $_SERVER['REMOTE_ADDR']; //浏览当前页面的用户计算机的ip地址
21     } else {
22         $ip = $_SERVER['REMOTE_ADDR'];
23     }
24     // IP地址合法验证
25     $long = sprintf("%u", ip2long($ip));
26     $ip   = $long ? array(
27         $ip,
28         $long
29     ) : array(
30         '0.0.0.0',
31         0
32     );
33     return $ip[$type];
34 }
35 
36 ?>

直接上代码。

posted @ 2018-06-12 17:24  HULANG-BTB  阅读(1690)  评论(0编辑  收藏  举报