PHP实现获取客户端IP并获取IP信息
程序员文章站
2022-06-14 11:46:09
代码很简洁,功能很实用,这里就不多废话了,直接奉上:
复制代码 代码如下:
<?php
/**
* 获取客户端ip
* @param integer $type 返回类型 0:string,1:long
* @return string|long
*/
function getclientip($type = 0) {
$ip = null;
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'];
}
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
/**
* 获取ip信息
* @param string|long $ip ip地址
* @return array
*/
function getipinfo($ip)
{
if (is_long($ip)) {
$ip = long2ip($ip);
}
$api = 'http://ip.taobao.com/service/getipinfo.php';
$ret = file_get_contents($api . '?ip=' . $ip);
$ret = json_decode($ret, true);
if ($ret['code'] == 0) {
return $ret['data'];
}
return array();
}
代码很简洁,功能很实用,这里就不多废话了,直接奉上:
复制代码 代码如下:
<?php
/**
* 获取客户端ip
* @param integer $type 返回类型 0:string,1:long
* @return string|long
*/
function getclientip($type = 0) {
$ip = null;
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'];
}
$long = sprintf("%u", ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
/**
* 获取ip信息
* @param string|long $ip ip地址
* @return array
*/
function getipinfo($ip)
{
if (is_long($ip)) {
$ip = long2ip($ip);
}
$api = 'http://ip.taobao.com/service/getipinfo.php';
$ret = file_get_contents($api . '?ip=' . $ip);
$ret = json_decode($ret, true);
if ($ret['code'] == 0) {
return $ret['data'];
}
return array();
}
以上就是本文的全部内容了,希望大家能够喜欢。