PHP Get Geolocation


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. $ip=$_SERVER['REMOTE_ADDR'];
  3. geoCheckIP($ip);
  4.  
  5. // print_r(geoCheckIP($ip));
  6. //Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen )
  7.  
  8. //Get an array with geoip-infodata
  9. function geoCheckIP($ip)
  10. {
  11. //check, if the provided ip is valid
  12. if(!filter_var($ip, FILTER_VALIDATE_IP))
  13. {
  14. throw new InvalidArgumentException("IP is not valid");
  15. }
  16.  
  17. //contact ip-server
  18. $response=@file_get_contents('http://www.netip.de/search?query='.$ip);
  19. if (empty($response))
  20. {
  21. throw new InvalidArgumentException("Error contacting Geo-IP-Server");
  22. }
  23.  
  24. //Array containing all regex-patterns necessary to extract ip-geoinfo from page
  25. $patterns=array();
  26. $patterns["domain"] = '#Domain: (.*?) #i';
  27. $patterns["country"] = '#Country: (.*?) #i';
  28. $patterns["state"] = '#State/Region: (.*?)<br#i';
  29. $patterns["town"] = '#City: (.*?)<br#i';
  30.  
  31. //Array where results will be stored
  32. $ipInfo=array();
  33.  
  34. //check response from ipserver for above patterns
  35. foreach ($patterns as $key => $pattern)
  36. {
  37. //store the result in array
  38. $ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found';
  39. }
  40.  
  41. return $ipInfo;
  42. }
  43.  
  44. ?>

URL: http://forrst.com/posts/PHP_Get_Geolocation-YVY

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.