php 根据IP查找地址的入门实例

前端之家收集整理的这篇文章主要介绍了php 根据IP查找地址的入门实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP根据IP查找地址,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:
  1. /**
  2. * 根据IP查找地址
  3. *
  4. * @param
  5. * @author 编程之家 jb51.cc jb51.cc
  6. **/
  7. function detect_city($ip) {
  8. $default = 'UNKNOWN';
  9. if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
  10. $ip = '8.8.8.8';
  11. $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
  12. $url = 'http://ipinfodb.com/ip_locator.PHP?ip=' . urlencode($ip);
  13. $ch = curl_init();
  14. $curl_opt = array(
  15. CURLOPT_FOLLOWLOCATION => 1,CURLOPT_HEADER => 0,CURLOPT_RETURNTRANSFER => 1,CURLOPT_USERAGENT => $curlopt_useragent,CURLOPT_URL => $url,CURLOPT_TIMEOUT => 1,CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],);
  16. curl_setopt_array($ch,$curl_opt);
  17. $content = curl_exec($ch);
  18. if (!is_null($curl_info)) {
  19. $curl_info = curl_getinfo($ch);
  20. }
  21. curl_close($ch);
  22. if ( preg_match('{<li>City : ([^<]*)</li>}i',$content,$regs) ) {
  23. $city = $regs[1];
  24. }
  25. if ( preg_match('{<li>State/Province : ([^<]*)</li>}i',$regs) ) {
  26. $state = $regs[1];
  27. }
  28. if( $city!='' && $state!='' ){
  29. $location = $city . ',' . $state;
  30. return $location;
  31. }else{
  32. return $default;
  33. }
  34. }

猜你在找的PHP相关文章