基本方法:
<?php //获取IP function get_ip() { if (isset($_SERVER)) { if (isset($_SERVER[HTTP_X_FORWARDED_FOR])) { $realip = $_SERVER[HTTP_X_FORWARDED_FOR]; } elseif (isset($_SERVER[HTTP_CLIENT_IP])) { $realip = $_SERVER[HTTP_CLIENT_IP]; } else { $realip = $_SERVER[REMOTE_ADDR]; } } else { if (getenv("HTTP_X_FORWARDED_FOR")) { $realip = getenv( "HTTP_X_FORWARDED_FOR"); } elseif (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } return $realip; } ?>
Thinkphp方法:
/** * 获取客户端IP地址 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 * @param boolean $adv 是否进行高级模式获取(有可能被伪装) * @return mixed */ function get_client_ip($type = 0,$adv=false) { $type = $type ? 1 : 0; static $ip = NULL; if ($ip !== NULL) return $ip[$type]; if($adv){ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown',$arr); if(false !== $pos) unset($arr[$pos]); $ip = trim($arr[0]); }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } }elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $long = sprintf("%u",ip2long($ip)); $ip = $long ? array($ip, $long) : array('0.0.0.0', 0); return $ip[$type]; }
souhu接口:
/** * 搜狐获取IP接口 * 返回类型 array 参数cip cid cname */ function get_sohu_ip($field=''){ $ip = file_get_contents('http://pv.sohu.com/cityjson?ie=utf-8'); preg_match('/{.+}/i', $ip, $m); $array = json_decode($m[0]); if(is_object($array)) { $array = (array)$array; } else if(is_array($array)) { foreach($array as $key=>$value) { $array[$key] = object_array($value); } } if(!empty($field)) return $array[$field]; return $array; }
输出:
Array ( [cip] => 223.198.110.24 [cid] => 460100 [cname] => 海南省海口市 )
这个方法有点问题,因为是通过PHP去访问,所以会直接获取当前服务器的IP
如果想获取某个客户访问的IP,可以通过在静态页(html)面设置
如:
<input name="ip" type="text" id="ip" value="" > <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> <script> document.getElementById('ip').value = returnCitySN["cip"]; </script>
以上方法是通过一个搜狐API获取当前客户IP,然后通过js将获取的IP赋予上面的表单里面,再通过该表单提交到PHP就可以获取。