Building an IP2Country lookup service with SQLite

Introduction

The IP address is a unique address used to communicate over the internet. In many countries the user gets a dynamically allocated IP address by his ISP. So usually you can't tell exactly to which city an IP gets allocated, but because of the fact that ISPs own IP ranges you can easily lookup the country of the ISP - and so the country the user is located in. The IANA is responsible for allocating these IP ranges to organisations. E.g. referring to this listing the IP range 18.0.0.0-18.255.255.255 (or 18/8 in CIDR notation) is allocated to the MIT which is located in the US. A user visiting your site with the IP 18.12.42.23 is either located in the US or using a web-proxy to falsify his identity.

Requirements

This tutorial requires you to have php5 installed as we use the PDO database abstraction layer to connect to an SQLite3 database. Attention: There is also a php module named php5-sqlite available - This module is for sqlite2 databases only and as we are using sqlite3 it doesn't fit our needs.

Getting the database

You can use whatever IP to country database you find on the net.. In this article I will use this one, because it's free, regularly updated and available in CVS format. Now we have two options: If you have "allow_url_fopen" set to "On" in the php.ini we just download the file using php, otherwise we'll have to do the update process manually by uploading the database file.

update.php

As mentioned before, if we have access to external addresses - we use it:

<?php /* URL of the zip-archive */ $url = "http://software77.net/cgi-bin/ip-country/geo-ip.pl?action=downloadZ"; /* Local filename */ $file = "IpToCountry.zip"; /* CSV file in zip */ $csv = "IpToCountry.csv"; /* Flag that determines if update is possible */ $update = false; /* We don't need html here.. */ header("Content-type: text/plain"); if(ini_get('allow_url_fopen')) { /* Download database */ $data = file_get_contents($url); /* On success.. */ if($data !== false) { /* Try to write the database into a file */ $out = file_put_contents($file, $data); /* On success.. */ if($out !== false) { $update = true; /* New File -> Update */ echo sprintf("Success: Wrote new database file with %d bytes\n", $out); } /* otherwise print error message */ else echo "Failure: Could write database file!"; } else echo "Failure: Could not download database file!"; } else { /* If there is a file (e.g. per ftp upload) we update.. */ if(file_exists($file)) { $update = true; } }

Attention: The zipped download file is approx. 1MB big - if your server has a slow connection or your traffic is limited consider to run the update only once a week.

Now that we have the source that either downloads

Comments (0) |

No comments yet!

Submit Comment