离线查询IP所属区域信息,国内精确到城市.国外精确到省份.

离线查询IP所属区域信息,国内精确到城市.国外精确到省份.

IP数据库来自ipip.net IPv4 数据库试用版,最后更新时间:20190703 试用版数据不含运营商,国外只具体到国家试用版不能作为正式商业用途

完整实例代码网盘下载:  http://share.menglei.net/file/16922972-449182665

IP数据库官方下载网址: https://www.ipip.net/product/client.html

PHP版解析源码: https://github.com/ipipdotnet/ipdb-php

PHP使用例子(来自wdja网站内容管理系统: https://github.com/shadoweb/wdja)

如果有兴趣,也可以集成纯真IP库会更精确一些,网上有现成的资源,可以自行测试.

function mm_ip_map($ip,$type=0){
  //离线查询IP所属区域信息,国内精确到城市.国外精确到省份.
  ini_set('memory_limit', '1G');
  spl_autoload_register(function ($class)
                        {
                          $class = str_replace("","/",$class);
                          if (strpos($class, 'ipip/db') !== FALSE)
                          {
                            require __DIR__.'/ip/'.$class.'.php';
                          }
                        }, true, true);
  $city = new ipipdbCity(__DIR__.'/ip/ipipfree.ipdb');
  if(ii_isnull($ip)) $ip = ii_get_client_ip();
  $ip = ii_get_lrstr($ip, ',', 'leftr');
  $ip_array = $city->findMap($ip, 'CN');
  $country = $ip_array['country_name'];
  $region = $ip_array['region_name'];
  $city = $ip_array['city_name'];
  $int = '';
  switch ($type)
  {
    case 0:
      $int = '';
      break;
    case 1:
      $int = '-';
      break;
    case 2:
      $int = '|';
      break;
    case 3:
      $int = '/';
      break;
    case 4:
      $int = '·';
      break;
    default:
      $int = '-';
      break;
  }
  if(ii_isnull($country)) {
    $res = '';
  }elseif(ii_isnull($region)){
    $res = $country;
  }elseif(ii_isnull($city)){
    $res = $country .$int .$region;
  }else{
    $res = $country .$int .$region .$int .$city;
  }
  return $res;
}
function ii_get_client_ip()
{
  $tclient_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  if(ii_isnull($tclient_ip))
  {
    $tclient_ip = $_SERVER['HTTP_CLIENT_IP'];
    if(ii_isnull($tclient_ip)) $tclient_ip = $_SERVER['REMOTE_ADDR'];
  }
  $tclient_ip = ii_get_safecode($tclient_ip);
  return $tclient_ip;
}
function ii_isnull($strers)
{
  if (trim($strers) == '') return true;
  else return false;
}
function ii_get_safecode($strers)
{
  if (!ii_isnull($strers))
  {
    $tstrers = $strers;
    $tstrers = str_replace(''', '', $tstrers);
    $tstrers = str_replace(';', '', $tstrers);
    $tstrers = str_replace('--', '', $tstrers);
    return $tstrers;
  }
}