This article mainly shares with you how PHP uses IP to match city information. I hope it can help everyone.
1. First, you need to obtain the user’s real ip
function ip(){ if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){ $ip = getenv('HTTP_CLIENT_IP'); }elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){ $ip = getenv('HTTP_X_FORWARDED_FOR'); }elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){ $ip = getenv('REMOTE_ADDR'); }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){ $ip = $_SERVER['REMOTE_ADDR']; } return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown'; }
2. Use a third-party interface to match the city
Note:
The matching city information needs to be stored in the database to facilitate later use
The API interface provided by the third party is currently relatively stable and easy to use from NetEase and Sina
1) Sina IP address query API interface
The data returned in json format is shown here
Interface: http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=IP address
Sample code: fragment
$ip = ip();$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip;$res = file_get_contents($url);echo $res;die;
The result is as shown:
2) NetEase Youdao IP address API interface
Interface: http://www.youdao.com/smartresult-xml/search.s?type=ip&q=IP address
Results As shown in the picture:
3) Taobao IP address library API interface
Interface: http://ip.taobao.com/service/getIpInfo.php?ip=[ip address string]
Sample code:
$ip = ip();$url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;$res = file_get_contents($url);echo $res;die;
The result is as shown in the figure:
3. Other IP address query interfaces and calling methods
Design cellular IP address query interface: http: //www.hujuntao.com/api/ip/ip.php
Tencent IP address query interface: http://fw.qq.com/ipaddress
Sina IP address query interface: http://int. dpool.sina.com.cn/iplookup/iplookup.php?format=js
Sohu IP address query interface: http://pv.sohu.com/cityjson
Google IP address query interface: http:// j.maxmind.com/app/geoip.js
Youdao IP address query interface: http://www.youdao.com/smartresult-xml/search.s
1616 IP address query interface: http:/ /w.1616.net/chaxun/iptolocal.php
126 http://ip.ws.126.net/ipquery
hao123 http://app.hao123.com/ipquery/getcity.php?rtype =2
Taobao http://ip.taobao.com/service/getIpInfo.php?ip=117.89.35.58
Pacific Computer Network http://whois.pconline.com.cn/
Related recommendations:
The above is the detailed content of How to use IP to match city information in php. For more information, please follow other related articles on the PHP Chinese website!