Getting Visitor's Country with PHP using Geo IP

Ask for programming support or advertise your custom programming and scripts here.

Getting Visitor's Country with PHP using Geo IP

Postby jwadmin » Sun May 17, 2009 9:12 am

Recently I needed to know what country my site visitors are coming from, to redirect a visitor to a different default web page based on the visitor's country of origin, and I went trhough this useful post on go4expert.com by Mary.

Here it is.

Introduction

Sometimes you just need to know what country your site visitors are coming from - for example, if you're trying to implement geo-targeted advertising. This article will show you how.

Sometimes you just need to know what country your site visitors are coming from - for example, if you're trying to implement geo-targeted advertising. That's where a tool like MaxMind's GeoIP comes in - it lets you easily extract geographic data from your visitor's IP address.

MaxMind makes available both commercial and free databases; the commercial ones are extremely precise and can get as fine-grained as the user's city, while the free version can only identify the country of origin. We'll use the free version in this article. If you need more detailed information, such as the remote client's city and state of origin, you will need to purchase a more detailed database from MaxMind.

Getting started

To use it, you'll have to first download the GeoIP Free Country file and extract it into a directory in your Web server. Then you'll have to pick which language API to use with the database file. For simplicity, we're going to use the pure PHP version because it doesn't require any additional configuration or Apache modules. Remember to read the license terms before installing these on your Web site to ensure you are in compliance.

The code in Listing A demonstrates the basics of using the module (geoip.inc) to access the GeoIP Free Country database (GeoIP.dat). The example assumes both the PHP include and the country database file are in the same directory as the PHP file itself. You'll have to change the paths as needed if this is not the case in your installation.

Code Listing A
Code: Select all
<?php

// include functions
include("geoip.inc");

// read GeoIP database
$handle = geoip_open("GeoIP.dat", GEOIP_STANDARD);

// map IP to country
echo "IP address 62.149.130.132 located in " . geoip_country_name_by_addr($handle, "62.149.130.132") . " (country code " . geoip_country_code_by_addr($handle, "62.149.130.132") . ")";

// close database handler
geoip_close($handle);

// print compulsory license notice
echo "<p> -- This product includes GeoIP data created by MaxMind, available from http://maxmind.com/ --";

?>


The sample code is pretty straightforward. After including the GeoIP PHP function library, the first step is to open the GeoIP database file with the geoip_open() function. This function accepts two arguments: the path to the database file and the type of database.

We then use the handle returned by the call to geoip_open() to obtain the two-letter country code and human-friendly name corresponding to the given IP address, via the geoip_country_code_by_addr() and geoip_country_code_by_name() functions, respectively. Both functions accept two arguments: the handle returned by geoip_open() and the IP address to resolve.

Once the required information is obtained, we close the database file with a call to geoip_close(). Simple as that.



Also you can block unwanted countries using the GeoIP Apache API.
The following Apache configuration directives uses GeoIP Country to block traffic from China and Russia:

Code: Select all
GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat

SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry
SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry
# ... place more countries here

Deny from env=BlockCountry

# Optional - use if you want to allow a specific IP address from the country you denied
# (See http://httpd.apache.org/docs/1.3/mod/mod_access.html for more details)
Allow from 10.1.2.3
User avatar
jwadmin
Site Admin
 
Posts: 25
Joined: Sat May 10, 2008 9:22 am

Redirect Web Visitors By Country Using PHP and MYSQL

Postby jwadmin » Sun May 17, 2009 9:22 am

It is also interesting this article by ip2location.com.

There are times when it is useful to redirect a visitor to different default web page based on the visitor's country of origin. One practical usage is to redirect visitor to web page with the language recognized by the visitor. This article shows you how to build up such a system using PHP (server side scripting language) and MYSQL (IP address to country lookup database).

Let us take a simple case study. Company XYZ is multi-national company with major customers from United States and Japan. The company official website is developed in both English and Japanese languages. The default page is in English language and visitor can switch to Japanese by changing the default language option. There exists a potential risk when a Japanese visitor does not understand English and he could not navigate the web site.

In this tutorial, we use the IP2Location™ IP-Country database to lookup country of origin from the visitor's IP address. Instead of loading the full database with 50000+ records, we could simplify this tutorial with assumption only two different IP address ranges in the world. IP addresses 0.0.0.0 - 126.255.255.255 originate from United States. Meanwhile, IP addresses 127.0.0.0 - 255.255.255.255 originate from Japan. Here we are creating a database "IP2Location" with table "IPCountry" that consists of two IP address range records.

Step 1: Create and connect to 'IP2Location' database
mysql> CREATE DATABASE IP2Location
mysql> CONNECT IP2Location

Step 2: Create 'IPCountry' table
mysql> CREATE TABLE IPCountry
--> (
--> ipFROM DOUBLE NOT NULL,
--> ipTO DOUBLE NOT NULL,
--> countrySHORT VARCHAR(2) NOT NULL,
--> countryLONG VARCHAR(100) NOT NULL,
--> PRIMARY KEY(ipFROM, ipTO)
--> );

Step 3. Import the 'ipcountry.csv' database into table 'IPCountry'
mysql> INSERT INTO IPCountry VALUES (0, 2130706431,'US','UNITED STATES');
mysql> INSERT INTO IPCountry VALUES (2130706432, 4294967295,'JP','JAPAN');

The full version of IP-Country database is available for subscription at $49/year from http://www.ip2location.com. If you have the full version of IP2Location™ IP-Country database, the import process is easier by using the LOAD DATA feature available in MYSQL.

PC:

mysql> LOAD DATA INFILE "/IPCountry.csv" INTO TABLE IPCountry FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Linux/Unix:

mysql> LOAD DATA INFILE "/IPCountry.csv" INTO TABLE IPCountry FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';

Let's assume the English web page as http://www.google.com and Japanese web page as http://www.google.co.jp. We implement a simple script index.php to detect visitor's country of origin. If the visitor is from Japan (with IP address range from 127.0.0.0 - 255.255.255.255), then it redirect him/her to web site in Japan, otherwise the United States. Simple? Here is the code and the comments serve as explanation index.php

<?php
// Replace this MYSQL server variables with actual configuration
$mysql_server = "mysql_server.com";
$mysql_user_name = "UserName";
$mysql_user_pass = "Password";

// Retrieve visitor IP address from server variable REMOTE_ADDR
$ipaddress = getenv(REMOTE_ADDR);

// Convert IP address to IP number for querying database
$ipno = Dot2LongIP($ipaddress);

// Connect to the database server
$link = mysql_connect($mysql_server, $mysql_user_name, $mysql_user_pass) or die("Could not connect to MySQL database");

// Connect to the IP2Location database
mysql_select_db("IP2Location") or die("Could not select database");

// SQL query string to match the recordset that the IP number fall between the valid range
$query = "SELECT * FROM IPCountry WHERE $ipno < = ipTO AND $ipno>=ipFROM";

// Execute SQL query
$result = mysql_query($query) or die("IP2Location Query Failed");

// Retrieve the recordset (only one)
$row = mysql_fetch_object($result);

// Keep the country information into two different variables
$countrySHORT = $row->countrySHORT;
$countryLONG = $row->countryLONG;

// Free recordset and close database connection
mysql_free_result($result); mysql_close($link);

// If the visitors are from JP, redirect them to JP site
if ($countrySHORT == "JP")
{
Header("Location: http://www.google.co.jp");
} else {
// Otherwise, redirect them to US site
Header("Location: http://www.google.com");
}
exit;

// Function to convert IP address (xxx.xxx.xxx.xxx) to IP number (0 to 256^4-1)
function Dot2LongIP ($IPaddr) {
if ($IPaddr == "")
{
return 0;
} else {
$ips = split ("\.", "$IPaddr");
return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
}
}
?>

Place this script as the default script of the web site. All visitors will go through this screening before redirect to an appropriate web page.
User avatar
jwadmin
Site Admin
 
Posts: 25
Joined: Sat May 10, 2008 9:22 am


Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron