ip2location facebbook  ip2location twitter  ip2location google+ ip2location github

Display Visitor's GeoLocation Using Web Service in PHP

Geolocation is a great way to put relevant content to your web visitors and it is a technology that can be used in almost any application you can think of.

In this tutorial, we use the IP2Location™ Web Service to lookup geolocation information from the visitor's IP address. Instead of loading the full database, you can also lookup IP address via our hosted web service.

Below are the sample codes written in PHP to query and display user's geolocation information.

 $urlTemplate = 'http://api.ip2location.com/?' . 'ip=%s&key=demo' . '&package=WS24&format=json';
 $host= gethostname();
 $ipAddress = gethostbyname($host);

 // replace the "%s" with real IP address
 $urlToCall = sprintf( $urlTemplate, $ipAddress);

 $rawJson = file_get_contents( $urlToCall );

 $geoLocation = json_decode( $rawJson, true );


		echo '';
		echo '
You are in local server!

'; echo ''; } }else{ echo 'IP Address parsing error!'; } ?> <html> <head> <title>IP2Location Web Service</title> </head> <body> <div> <center>Hello World!</center><br> </div> <div> <center>Your IP address <?php echo $ipAddress; ?></center> <center> <?php if(isset($geoLocation['country_code'])&&isset($geoLocation['country_name'])&&isset($geoLocation['region_name'])&&isset($geoLocation['city_name'])&&isset($geoLocation['latitude'])&&isset($geoLocation['longitude'])&&isset($geoLocation['zip_code'])&&isset($geoLocation['time_zone'])){ echo '
Country Code:'."\n". $geoLocation['country_code'] . "\n
"; echo 'Country Name:'."\n". $geoLocation['country_name'] . "\n
"; echo 'Region Name:'."\n". $geoLocation['region_name'] . "\n
"; echo 'City Name:'."\n". $geoLocation['city_name'] . "\n
"; echo 'Latitude:'."\n". $geoLocation['latitude'] . "\n
"; echo 'Longitude:'."\n". $geoLocation['longitude'] . "\n
"; echo 'Zip code:'."\n". $geoLocation['zip_code'] . "\n
"; echo 'Time zone:'."\n". $geoLocation['time_zone'] . "\n
"; }else{ echo 'IP Address parsing error!'; } ?> </center> </div> </body> </html>


Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.