A recent project required the display of geographical distribution information, so I took a closer look at IP and provincial and municipal information.
The following two solutions were used to implement the acquisition of user surrounding information
1. The IP library is used, the pure IP library, but the database update is slow, the file is huge, and it takes up a lot of resources.
2. Call the IPSEARCH service of open.baidu.com and use the IP138 database to obtain the province and city information where the IP is located. Then search the local database (region table of ecshop) to get the corresponding regionid, and associate it through the ID. Data
I tested it today and it feels good and I will post the implementation code.
/**
* Get information about the city where the IP is located
* TODO: IP address cache needs to be constructed
* @param string $ip
*/
function get_city($ip=null) {
import('ORG.Util.Utility');
$array = array();
$d = M('region');
//TODO: You can construct a cache here to improve loading speed, search the city list here $cities = $d->where('`regiontype`=2')-> ;select(); $ip = ($ip) ? $ip : get_client_ip();
$url = "http://open.baidu.com/ipsearch/s?wd={$ip}&tn=baiduip ";
$res = mb_convert_encoding(Utility::HttpRequest($url), 'UTF-8', 'GBK');
if ( preg_match('#From: (.+)< ;/b>#Ui', $res, $m) ) {
foreach( $cities AS $value) {
if ( FALSE !== strpos($m[1], $value['regionname ']) ) {
//Return the IP information of the city
$array['c']=$value;
$array['p']=$d->where('` regionid`='.$value['parentid'])->find();
return $array;
}
}
}
return array();
}
The result returned by the call is as follows array
'c' =>
array
'regionid' => string '386' (length=3)
'parentid' => string '31' (length=2)
'regionname' => string 'Jinhua' (length=6)
'regiontype' => string '2' (length=1)
'agencyid ' => string '0' (length=1)
'ename' => string 'jinhua' (length=6)
'p' =>
array
'regionid' => string '31' (length=2)
'parentid' => string '1' (length=1)
'regionname' => string 'Zhejiang' (length=6)
'regiontype' => string '1' (length=1)
'agencyid' => string '0' (length=1)
'ename' => string 'zhejiang' (length= 8)
I tested it using IP, and the information is quite accurate. The IP database of IP138 and the database of 123CHA are both relatively comprehensive in the domestic time database. In this way, the performance is okay. .