IP Geo Targeting in PHP–The EASY Way!

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

I recently decided to implement the Ebay Partner Program into my website as the Google Affiliate Network was making me nothing.

One of the biggest problems though is, when using the “Widgets” you do not get Geo Targeting, so you have to create a different Banner for each country and implement a way to target those available countries as required.

After doing some searching on the internet for the easiest to implement solution, I came across a very easy to use API by hostip.info.

hostip is pretty simple to use, all you have to do is make a connection to a API url with the IP address you wish to locate and it can return all sorts of information like LAT/LONG and/or the country the IP address is from – here is a sample URL you can check right now:

http://api.hostip.info/country.php?ip=64.233.160.5

As you can see it returns “US” which is the 2 character country code for the United States. We can implement this into PHP to get the current visitors country by using this code:

$ip = $_SERVER [ 'REMOTE_ADDR' ]; 
$country = file_get_contents ( 'http://api.hostip.info/country.php?ip=' . $ip ); 

$country will now hold the country code (remember it is in UPPER CASE). You can then simply check what the value is and target an advert or particular content depending on the user:

if ( $_SESSION['country'] == "GB" ) { 
	echo "You are from the UK!";
}

 

External Requests

Please bare in mind that you are requesting information from an external source, depending on server health and traffic, the response may take from milliseconds to minutes to complete. So as a precaution you should “save” the result so that you do not have to keep requesting the information from hostip.info. Here is an example code that you could use:

if (!isset($_SESSION['country'])) {
	$ip = $_SERVER [ 'REMOTE_ADDR' ]; 
	$_SESSION['country'] = file_get_contents ( 'http://api.hostip.info/country.php?ip=' . $ip ); 
}

You can now access the value from $_SESSION['country'], once this has been set it will no longer ask the external source saving them bandwidth and you loading time.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips