Home > php教程 > PHP源码 > body text

超简单的php获取ip地址信息的接口范例

WBOY
Release: 2016-06-08 17:20:12
Original
1494 people have browsed it

获取ip地址信息的接口在网上可以找到一堆了,我们现在主要使用的是淘宝,百度,ip138及新浪的了,下面我们来看一个调用ip138的ip地址例子吧。

<script>ec(2);</script>

通过php获取ip所属地的接口,要是自己弄一个ip库的话,会比较麻烦,而且需要经常更新,所以不现实。网上找了一些接口,发现好多都不能用了,于是自己写了一个,通过抓ip138页面来提取信息。只要它不改版,这个就能永久有效。

响应比较快,小网站用此接口完全没有问题,代码如下:

 header("Content-type:text/html;charset=utf-8");
 $ip = checkip(@$_GET['ip']);
 if(!$ip)
 {
  exit( json_encode( array('error'=>1, 'msg'=>'参数ip不正确') ) );
 }
 $url = 'http://www.ip138.com/ips1388.asp?ip='.$ip.'&action=2';
 $ipInfo = file_get_contents($url);
 $ipInfo = iconv('gb2312', 'utf-8', $ipInfo);
 preg_match('/

  • 本站主数据:(.*)
  • /i', $ipInfo, $info);
     if($info[1])
     {
      exit( json_encode( array('error'=>0, 'pos'=>$info[1]) ) );
     }
     else
     {
      exit( json_encode( array('error'=>1, 'msg'=>'解析失败') ) );
     }

     /**
      * 验证ip格式是否正确
      */
     function checkip($ip)
     {
      $ip = substr($ip, 0, 15); //ipv4最多只有这么长
      if( !preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $ip) )
      {
       return false;
      }
      else
      {
       return $ip;
      }
     }
    ?>

    访问形式为:localhost/ip.php?ip=xxx.xxx.xxx.xxx。带一个参数就行了,返回为json格式的数据

  • Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Recommendations
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!