Geotargeting PHP Code

I have joined Google and none of the tools on eKstreme.com are official Google tools nor are they endorsed by Google. See this.

IP Database Explanation

With the database ready, let's take a look at what each field means:

FieldType
IP_STARTThe start of the IP range.
IP_ENDThe end of the IP range.
IP_FROMThe start of the IP range, as a long number.
IP_TOThe end of the IP range, as a long number.
COUNTRY_CODE2A two-letter country code, such as 'UK'.
COUNTRY_NAMEThe full country name, such as 'Germany'.

Geotargeting PHP Code

The code is very simple:

And the code is:

$DatabaseServer = "YOUR_DATABASE_SERVER";
$Username = "YOUR_DATABASE_USERNAME";
$Password = "YOUR_DATABASE_PASSWORD";
$DatabaseName = "YOUR_DATABASE_NAME";
 
$link = mysql_connect($DatabaseServer, $Username, $Password) or die('Could not connect: ' . mysql_error());
mysql_select_db($DatabaseName) or die('Could not select database');
$IP = $_SERVER["REMOTE_ADDR"]; //Get the IP address
$res = mysql_query("SELECT country_code2,country_name FROM IPCountries WHERE IP_FROM<=inet_aton('$IP') AND IP_TO>=inet_aton('$IP')");//look up IP address
 
$Codes = mysql_fetch_array($res); //get result
$CountryCode = $Codes['country_code2']; //two-letter country code
$CountryName = $Codes['country_name']; //full country name
echo "$CountryCode - $CountryName"; //print it out, just as an example
 
mysql_close($link); //clean up

In this example, we simply printed out the country code and name. In a real-world example, you could use this information to target content. For example, to output content for IP addresses from France, you could use:

if($CountryCode == "FR"){
  //echo contents for France
  echo "Bonjour!"
  }
else{
  //default content
  echo "Hello!"
  }

Next page: Flags and closing remarks.