How to get the country of an IP address in PHP?

The HostIP.info provides API allows you to get the country including the city as well. The simple PHP script that can get the country is as follow:

<?php
 
get_country_by_ip();
 
function get_country_by_ip()
{
	$ip = $_SERVER['REMOTE_ADDR']; /** Get the remote client IP */
	$url='http://api.hostip.info/get_html.php?ip='.$ip;  /** Prepare the URL to hostip.info **/
 
	$data=file_get_contents($url);
 
	echo $data;
 
}
 
?>

A working example is here which prints out the country and even city of the IP address that you’re located now.

Update: The HostIP.info also allows additional parameter position=true that will return more complete information including the latitude and longitude of where you’re located. A more thorough example is included below which includes the “Country”, “City”, “Latitude”,”Longitude”, “IP”, returned in an associative array, which you can then segregate the data easily such as to store them in your database. And the Latitude and longitude will be useful so you can display them on the Google Map or plot all the red dots on a Google Map to reveal your visitors from different countries. Take a look at the 2nd example below:

2nd example

<?php
 
$a=get_country_by_ip();
 
echo "<p>Country :".$a['Country']."</P>";
echo "<p>City :".$a['City']."</P>";
echo "<p>Latitude :".$a['Latitude']."</P>";
echo "<p>Longitude :".$a['Longitude']."</P>";
echo "<p>IP Address :".$a['IP']."</P>";
 
function get_country_by_ip()
{
	$ip =$_SERVER['REMOTE_ADDR'];
	$url='http://api.hostip.info/get_html.php?ip='.$ip.'&position=true';
 
	$data=file_get_contents($url);
	$a=array();
	$keys=array('Country','City','Latitude','Longitude','IP');
	$keycount=count($keys);
	for ($r=0; $r < $keycount ; $r++)
	{
		$sstr= substr ($data, strpos($data, $keys[$r]), strlen($data));
		if ( $r < ($keycount-1))
			$sstr = substr ($sstr, 0, strpos($sstr,$keys[$r+1]));
		$s=explode (':',$sstr);
		$a[$keys[$r]] = trim($s[1]);
	}
 
	return $a;
 
}
 
?>

Enter your email address to subscribe our newsletter or feed for FREE:

Delivered by FeedBurner


Bookmark with:

[Delicious]    [Digg]    [Reddit]    [Facebook]    [StumbleUpon]

1 Response to “How to get the country of an IP address in PHP?”


  1. 1 IP to country converter – using MaxMind GeoIP API | AjaxApp.com

Leave a Reply

You must login to post a comment.