Building Sample Programs for an IP-to-country Mapping Application

Undeniably, the ability to determine from which countries visitors are accessing a particular web site can be useful, and not only for statistical purposes. With this information at your disposal, it’s possible to instruct the site to deliver its content in different languages, a feature that users worldwide will appreciate. This second part of a four-part series moves you in that direction with some sample programs.

Introduction

Building a web site that will be seated on a multi-lingual platform often requires developing an IP-to-country application that permits you to map users’ IP addresses to their corresponding countries. Thus, if you’re interested in learning how to create an application like this, which can be easily incorporated into any existing web site, then this series of articles might be what you’re looking for.

Of course, if you already read the initial chapter of this series, then you’re already familiar with creating the basic structure of the aforementioned IP-mapping program. In that tutorial I explained how to create a lookup MySQL table by importing the contents of the IP-to-country database, available for free at Webnet77.

This database contains over 82,0000 records and allows you to map more than 3,200,000 IP addresses to their respective countries. This can be really handy for developing different IP-to-country applications with minor efforts.

Since I already discussed how to create a mapping MySQL table by using the lookup database, in this second article I’m going to appeal to the functionality of this table to build a couple of sample PHP applications. These applications will be capable of determining from which country visitors are accessing a web page, in accordance with their IP addresses.

Now, it’s time to get rid of the preliminaries and start developing these simple — yet efficient — IP-to-country programs with PHP. Let’s jump in!

{mospagebreak title=Review: building an IP-to-country mapping MySQL table with a lookup database file}

In case you haven’t had the chance to read the preceding article of this series, in the next few lines I’m going to list for you all of the source files required for building an IP-to-country MySQL table. I will be using the records of the source lookup database, previously downloaded from Webnet77’s web site.

That being said, here are the corresponding definitions for each of these files:


(definition of ‘create_ip_to_country_table.sql’ file)


CREATE TABLE ‘iptocountry’ (

‘lower_bound’ INT(11) UNSIGNED NOT NULL default ‘0’,
‘upper_bound’ INT(11) UNSIGNED NOT NULL default ‘0’,
‘owner’ VARCHAR(20) NOT NULL,
‘last_updated’ INT(11) DEFAULT NULL,
‘two_chars_country’ CHAR(2) NOT NULL default ”,
‘three_chars_country’ CHAR(3) NOT NULL default ”,
‘country’ VARCHAR(100) NOT NULL default ”

);



(definition of ‘populate_table.php’ file)

<?php


try{

// connect to MySQL server

if(!$db=mysql_connect(‘host’,’user’,’password’)){

throw new Exception (‘Error connecting to the server.’);

}

// select database

if(!mysql_select_db(‘database’,$db)){

throw new Exception (‘Error selecting database.’);

}

// set timeout limit (handy when working with slower machines)

set_time_limit(360);

// open ‘iptocountry.csv’ file for further reading

if(!$fp=fopen(‘iptocountry.csv’,’r’)){

throw new Exception (‘Error reading source file.’);

}

// read file and populate ‘iptocountry’ MySQL table with each line of file

while(!feof($fp)){

$line=str_replace(‘"’,”,fgets($fp));

// check to see if current line is not a comment

if(substr($line,0,1)!=’#’){

// explode values

$values=explode(",",$line);

if(count($values)!=1){

// build query

$sql="INSERT INTO iptocountry VALUES (‘".implode("’,’",$values)."’)";

// run query against MySQL table

mysql_query($sql);

}

}

}

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


?>


The two files listed above contain all the source code required for creating an IP-to-country mapping MySQL table. In this case, the first SQL file is responsible for creating the structure of the table in question, while the second one is tasked with importing the records of the source lookup database, which was previously downloaded as a CSV file from Webnet77’s web site.

Now that you remember how the previous source files do their things, it’s time to build a pair of simple PHP applications. These applications will take advantage of the functionality of the "iptocountry" MySQL table created in the previous tutorial to map the IP addresses of different users to their originating countries.

To learn how these sample PHP programs will be developed, please click on the link that appears below and keep reading.

{mospagebreak title=Mapping IP addresses to originating countries with a basic geo location application}

To be frank, building a PHP application that permits you to determine from which country a user is accessing a web page according to his/her IP address is a straightforward process that can be tackled with minor efforts.

Basically, this procedure is reduced to performing two simple steps: first, capturing the user IP address and second, determining via the "iptocountry" MySQL table which country is tied to that particular address.

However, to clarify this concept a bit further, I coded a sample PHP script (shown below) which accomplishes all the tasks mentioned above. Here it is:


try{

// connect to MySQL server

if(!$db=mysql_connect(‘host’,’user’,’password’)){

throw new Exception (‘Error connecting to the server.’);

}

// select database

if(!mysql_select_db(‘alejandro’,$db)){

throw new Exception (‘Error selecting database.’);

}

// get user IP address

$ip=sprintf(‘%u’,ip2long($_SERVER[‘REMOTE_ADDR’]));

// Map IP Address to country using ‘iptocountry’ database

if(!$result=mysql_query("SELECT country FROM iptocountry WHERE lower_bound <=$ip AND upper_bound >= $ip LIMIT 1")){

throw new Exception (‘Unable to map IP Address to country.’);

}

// get row from database table

$row=mysql_fetch_array($result);

// display country which user is accessing from

echo ‘Welcome dear visitor, you are accessing our web site from : ‘.$row[‘country’];

}

catch(Exception $e){

echo $e->getMessage();

exit();


}


See how simple it is to determine from which country a visitor is accessing a web page by means of the "iptocountry" MySQL table? I guess you do! But, to dissipate any doubts, please take a close look at the above code sample.

As you can see, it first connects to MySQL and selects a fictional database, and then it gets the IP address of the user currently visiting the web page. Finally, it determines the country that corresponds to that specific address.

Naturally, this last step is performed by querying the "iptocountry" MySQL table to find out to which range of addresses the user’s IP address belongs. In this case, the values stored on the "lower_bound" and "upper_bound" fields are utilized for performing this comparison and for mapping the IP address to its originating country. That’s all.

So, suppose that I am the one who is accessing the previous script. It would produce the following output:

‘Welcome dear visitor, you are accessing our web site from : ARGENTINA

Pretty neat, right? At this point, you hopefully realized how easy it is to build an IP-to-country program with PHP using a procedural approach. As you might have guessed, however, it’s also feasible to develop a similar application by means of the object-oriented paradigm.

Therefore, the last section of this tutorial will be aimed at illustrating how to create a lookup program by using a basic MySQL abstraction class.

The complete details regarding the definition of this class will be revealed in the following section. Please click on the link that appears below and read the next few lines.


{mospagebreak title=Developing an object-oriented geo-location PHP application}

In the previous segment, I showed you how to build a procedural PHP script which was capable of mapping users’ IP addresses to their corresponding countries via the "iptocountry" MySQL table. Thus, in this last section of the article, I’d like to demonstrate how this same task can be performed by way of an object-oriented approach.

To do this, I’m simply going to create a basic MySQL abstraction class, which will carry out the IP-to-country mapping process by means of a simple interface. The signature of this class, along with an example of how to use it, is listed below:


// define ‘MySQL’ class

class MySQL{

private $mysqli;

private $result;

public function __construct($host=’host’,$user=’user’,$password=’password’,$database=’database’){

// connect to MySQL and select database

$this->mysqli=new mysqli($host,$user,$password,$database);

if(mysqli_connect_errno()){

throw new Exception(‘Error connecting to MySQL: ‘.$this->mysqli->error);

}

}

// run SQL query

public function query($query){

if(!$this->result=$this->mysqli->query($query)){

throw new Exception(‘Error running SQL query: ‘.$this->mysqli->error);

}

}

// fetch one row

public function fetchRow(){

while($row=$this->result->fetch_assoc()){

return $row;

}

return false;

}

}


try{

// connect to MySQL and select database

$db=new MySQL(‘host’,’user’,’password’,’database’);

// get user IP address

$ip=sprintf(‘%u’,ip2long($_SERVER[‘REMOTE_ADDR’]));

// Map IP Address to country using ‘iptocountry’ database

$db->query("SELECT country FROM iptocountry WHERE lower_bound <=$ip AND upper_bound >= $ip LIMIT 1");

// get row from database table

$row=$db->fetchRow();

// display country which user is accessing from

echo ‘Welcome dear visitor, you are accessing our web site from : ‘.$row[‘country’];

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


If you develop object-oriented applications with PHP on a frequent basis, then you’ll grasp the logic that drives the above script in a snap. In this particular situation, users’ IP addresses are directly mapped to their respective countries by performing the same SQL query used with the procedural example. In this case the "iptocountry" table is queried by means of the "MySQL" accessing class shown before.

Finally, as usual with many of my articles on PHP development, feel free to improve all of the code samples included in this article, and use them as a guide for developing different, more creative IP-to-country mapping applications.

Final thoughts

Over the second installment of this series, you hopefully learned how to take advantage of the "iptocountry" MySQL table created in the preceding tutorial to develop a couple of geo-location applications with PHP.

First I used a procedural approach to build the application, and then, in the second example, I showed you how to build it using the object-oriented paradigm. Of course, both programs offer practically the same level of functionality, so feel free to pick the one that best suits your needs.

In the upcoming tutorial, I’ll be discussing how to generate dynamic web pages in different languages, naturally by using the previous MySQL lookup table. Therefore, now that you know what the next article will be about, you can’t miss it!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye