Using Code Igniter to Build an IP-to-Country Mapping Application

Adding geo-location capabilities to a web site isn’t too hard; it’s possible to develop an IP-to-country mapping program with PHP, which can be incorporated into a site in a few easy steps. If you’re interested in learning how to build this application, then keep reading. This is the final installment of a four-part series that covers developing an IP-to-country mapping application with PHP.

Introduction

As you would expect, this series walks you through building an IP-to-country lookup table with MySQL, and teaches you how to take advantage of its functionality for creating different IP mapping web-based programs.

Speaking of web-based programs, you may recall that in the previous part of the series, I explained how to use the IP-to-country lookup MySQL table for generating web pages in different languages.

Speaking more specifically, I created two sample applications with PHP. The first one was capable of constructing dynamically a hypothetical "products" web page section, based on the countries from which the page was being accessed, while the second example demonstrated how to build entire web documents.

So far, you shouldn’t have major problems understanding how these two sample applications were developed, since the logic implemented by them was very simple to follow. However, I have to admit that these examples were pretty primitive and certainly can stand some improvement before being used in production environments.

With that idea in mind, in this final chapter of the series, I’ll be discussing how to build multi-lingual web pages by combining the functionality brought by the "iptocountry" MySQL table that you learned in previous tutorials and the power of the Code Igniter PHP framework.

Now that you know what to expect from this article, it’s time to move forward and learn how to use Code Igniter to generate dynamic web pages in different languages. Let’s go!

{mospagebreak title=Review: Building dynamic web pages in distinct languages using the iptocountry MySQL table}

In case you haven’t had an opportunity to read the preceding article of the series, below I’ve reintroduced the two hands-on examples built in that tutorial. The article showed how to create multi-lingual web pages by using the already familiar "iptocountry" MySQL table. And now for the examples:

(example on building a ‘product’ web page section in different languages)


// define ‘MySQL’ class

class MySQL{

private $mysqli;

private $result;

public function __construct($host=’localhost’,$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 two_chars_country FROM iptocountry WHERE lower_bound <=$ip AND upper_bound >= $ip LIMIT 1");

// get row from database table

$row=$db->fetchRow();

// fetch contents from ‘products’ MySQL table based on 2-char country code

$db->query(‘SELECT id,name,description FROM products_’.$row[‘two_chars_country’]);

while($row=$db->fetchRow()){

// display products list and provide a link to a details page

echo ‘<h2>Product :’.$row[‘name’].'</h2><p>Description :’.$row[‘description’].'</p>’;

echo ‘<p><a href="details.php?id=’.$row[‘id’].’">View product details</a></p>’;

}

}

catch(Exception $e){

echo $e->getMessage();

exit();

}



(example on building entire web pages in different languages)


// define ‘MySQL’ class

class MySQL{

private $mysqli;

private $result;

public function __construct($host=’localhost’,$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;

}

}


// this is the front controller

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 three_chars_country FROM iptocountry WHERE lower_bound <=$ip AND upper_bound >= $ip LIMIT 1");

// get row from database table

$row=$db->fetchRow();

// get 3-char country code

$code=$row[‘three_chars_country’];

// generate web page depending on country code

require_once ‘header_’.$code.’.php’;

require_once ‘body_’.$code.’.php’;

require_once ‘footer_’.$code.’.php’;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


As shown previously, the two code samples above demonstrate how to exploit the functionality of the "iptocountry" MySQL lookup table to build different kind of web applications. In the first case, the table in question is used to generate a fictional "products" page section in a multi-lingual fashion, while the last example illustrates how to build entire web pages by means of a simple front controller.

So far, so good. At this moment, hopefully you’re familiar with the basics of building dynamic web documents using a MySQL mapping table and PHP. So what’s next? Well, as I explained in the introduction, my goal here is to demonstrate how this MySQL table can be utilized in conjunction with the Code Igniter PHP framework to build a simple IP-to-country mapping application.

Thus, if you’re a strong advocate of using the Model-View-Controller pattern, then the examples that I plan to develop in the next section will surely appeal to you.

Click on the link that appears below and keep reading.

{mospagebreak title=Building a simple IP-to-country mapping application with the Code Igniter framework}

If you’re not familiar with the Code Igniter framework, don’t worry; the program that I’m going to build in the next few lines will be pretty straightforward. In simple terms, any web application developed with this framework will be composed of three separate modules, based on the Model-View-Controller approach: first the controller, which is charged with handling application logic; then the model, which handles business logic, generally in the form of database tables or a data access layer; and finally, one or more views, usually represented by a set of HTML pages.

So, first I’m going to define a "Products" controller. It will handle the logic required to generate a fictional, multi-lingual "products" web page section. Finally, I’m going to create a view file, tasked with displaying these products as a simple web document.

The prototype of the controller class looks like this:


<?php


// define ‘Products’ controller class

class Products extends Controller{

function Products(){

// load controller parent

parent::Controller();

// load database class and connect to MySQL

$this->load->database();

}

// display products list

function index(){

// get user IP address and check to see if it’s valid

if($this->input->valid_ip($this->input->server(‘REMOTE_ADDR’))){

$ip= sprintf(‘%u’,ip2long($this->input->server(‘REMOTE_ADDR’)));

// get 3-char country code

$this->db->select(‘three_chars_country’);

$code=$this->db->get_where(‘iptocountry’,array(‘lower_bound <=’ => $ip,’upper_bound =>’ => $ip);

// get products list from country code-based MySQL table

$products=$this->db->get(‘products_’.$code);

// load ‘products’ view depending on country code

$this->load->view(‘products_’.code’.php’,$products);

}

}

}

?> 


To put it simply, the above "Products" controller starts loading the database class that comes bundled with Code Igniter, which is used within the "index()" method, to fetch the contents from different "products" MySQL tables, depending on the countries from which users are accessing this fictional web site.

In the end, the controller finishes its execution by loading the appropriate view file and embedding the product-related data into it. This short example should give you an idea of how to generate a "products" web page in several languages using Code Igniter.

However, the missing piece of this schema is the view file that renders these products in the form of a basic web document. Thus, in the final section of this tutorial I’m going to build this file.

Therefore, click on the link that appears below and read the following segment. We’re almost done!

{mospagebreak title=Finishing the IP-to-country mapping application}

In the previous section, I explained how to build a simple controller class to implement the logic required to generate a "products" web page section in different languages. Assuming that you understand how this controller works, it’s time to create the generic view file that renders this product-related data in the form of a web page.

That being said, here’s how this simple view file looks:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<?php foreach($products->result_array() as $product):?>

<div id="container">

<h2><?php echo $product[‘name’];?></h2>

<p><?php echo $product[‘description’];?></p>

<p><?php echo $product[‘price’];?></p>

<p><?php endforeach;?></p>

</div>

</body>

</html>


As you can see, the above view file implements the logic necessary to loop through these fictional products and displays their different items, including their names, descriptions and prices respectively. Simple and effective!

Having shown you how to define a basic view file with Code Igniter, the development of this IP-to-country application is completed. Of course, this is only an illustrative example that demonstrates how to build a program like this using Code Igniter, but you shouldn’t have major troubles adapting the source code for working with a different framework.

Final thoughts

It’s hard to believe, but we’ve come to the end of this series. Hopefully, this journey has been useful, since you learned how to build different sorts of IP-to-country mapping applications with PHP using a single MySQL lookup table. From this point onward, you can use all of the code samples included in these tutorials and start creating your own mapping programs in PHP.

See you in the next PHP web development tutorial!

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

chat sex hikayeleri Ensest hikaye