
本文共 1574 字,大约阅读时间需要 5 分钟。
PHP对客户IP的操作
有很多学PHP的小伙伴取客户IP的时候不够精确,下面是比较精确的方法,拿小本本记一下!获取客户端IP地址function get_client_ip($type = 0,$adv=true) {
$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];
}获取IP归属地function get_ip_city($ip){
$ch = curl_init();
$url = 'https://whois.pconline.com.cn/ipJson.jsp?ip='.$ip;
//用curl发送接收数据
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//请求为https
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$location = curl_exec($ch);
curl_close($ch);
//转码
$location = mb_convert_encoding($location, 'utf-8','GB2312');
//var_dump($location);
//截取{}中的字符串
$location = substr($location, strlen('({')+strpos($location, '({'),(strlen($location) - strpos($location, '})'))*(-1));
//将截取的字符串$location中的‘,’替换成‘&’ 将字符串中的‘:‘替换成‘=’
$location = str_replace('"',"",str_replace(":","=",str_replace(",","&",$location)));
//php内置函数,将处理成类似于url参数的格式的字符串 转换成数组
parse_str($location,$ip_location);
return $ip_location['addr'];
}
转载地址:https://blog.csdn.net/weixin_33958381/article/details/116252380 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
关于作者
