Posted By

Hexahow on 12/06/13


Tagged

LongitudeLatitudeIP addressGeolocation


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Get Longitude and Latitude by IP address in PHP


 / Published in: PHP
 

URL: http://www.ip2location.com

// description of your code here /********************************************************************************/ /* Description: Get Longitude and Latitude by IP address in PHP / / For information, please visit http://www.ip2location.com */ /********************************************************************************/

  1. // description of your code here
  2. /********************************************************************************/
  3. /* Description: Get Longitude and Latitude by IP address in PHP */
  4. /* For information, please visit http://www.ip2location.com */
  5. /********************************************************************************/
  6.  
  7. <?php
  8.  
  9. $api_key = "insert api key here";
  10. $ip_addr = get_remote_ip_address();
  11. //Only IP2Location Web Service package WS5, WS9 and WS10 contains latitude and longitude information
  12. $package = "insert package number";
  13.  
  14. $service_url = "http://api.ip2location.com/?ip=$ip_addr&key=$api_key&package=$package";
  15.  
  16. //Setting up connection using the service url
  17. $ch = curl_init();
  18. curl_setopt($ch, CURLOPT_URL, $service_url);
  19. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  20. $result = curl_exec($ch);
  21.  
  22. $temp = $result;
  23. $result_split = explode(";", $temp);
  24. //Retrieving latitude and longitude information from the result returned by the API
  25. $latitude = $result_split[4];
  26. $longitude = $result_split[5];
  27.  
  28. echo $temp . "<br />";
  29. echo "latitude : " . $latitude . "<br />";
  30. echo "longitude : " . $longitude . "<br />";
  31.  
  32. function get_remote_ip_address()
  33. {
  34. // Check to see if an HTTP_X_FORWARDED_FOR header is present.
  35.  
  36. if($_SERVER['HTTP_X_FORWARDED_FOR'])
  37.  
  38. {
  39.  
  40. // If the header is present, use the last IP address.
  41. $temp_array = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  42. $temp_ip_address = $temp_array[count($temp_array) - 1];
  43. }
  44. else
  45. {
  46. // If the header is not present, use the
  47. // default server variable for remote address.
  48. $temp_ip_address = $_SERVER['REMOTE_ADDR'];
  49. }
  50.  
  51. return $temp_ip_address;
  52. }
  53. ?>

Report this snippet  

You need to login to post a comment.