Posted By

iTony on 09/24/12


Tagged

php detection geo


Versions (?)

Detect City by IP function


 / Published in: PHP
 

URL: http://www.catswhocode.com/blog/useful-php-code-snippets-and-functions

This will take an IP and try to find the city.

  1. function detect_city($ip) {
  2.  
  3. $default = 'UNKNOWN';
  4.  
  5. if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
  6. $ip = '8.8.8.8';
  7.  
  8. $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)';
  9.  
  10. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
  11. $ch = curl_init();
  12.  
  13. $curl_opt = array(
  14. CURLOPT_FOLLOWLOCATION => 1,
  15. CURLOPT_HEADER => 0,
  16. CURLOPT_RETURNTRANSFER => 1,
  17. CURLOPT_USERAGENT => $curlopt_useragent,
  18. CURLOPT_URL => $url,
  19. CURLOPT_TIMEOUT => 1,
  20. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  21. );
  22.  
  23. curl_setopt_array($ch, $curl_opt);
  24.  
  25. $content = curl_exec($ch);
  26.  
  27. if (!is_null($curl_info)) {
  28. $curl_info = curl_getinfo($ch);
  29. }
  30.  
  31. curl_close($ch);
  32.  
  33. if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) ) {
  34. $city = $regs[1];
  35. }
  36. if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) {
  37. $state = $regs[1];
  38. }
  39.  
  40. if( $city!='' && $state!='' ){
  41. $location = $city . ', ' . $state;
  42. return $location;
  43. }else{
  44. return $default;
  45. }
  46.  
  47. }

Report this snippet  

You need to login to post a comment.