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

The 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:

function get_country_by_ip()
	$ip = $_SERVER['REMOTE_ADDR']; /** Get the remote client IP */
	$url=''.$ip;  /** Prepare the URL to **/
	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 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

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()
	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 |

Leave a Reply

You must login to post a comment.