I18N_IP2Country - IP Address to Country Code Conversion
September 19th, 2005
Provides methods for retrieveing country name or ISO 3166 country code based on ip address, ie. ip to country conversion.
Provides methods for retrieveing country name or ISO 3166 country code based on ip address, ie. ip to country conversion.
Proper documentation to be written. In the meanwhile these straightforward examples will server as documentation.
Documentation
Create a pulldown with users country selected by default.
<?php
/* create country pulldown with users country selected */
/* as default */
require_once('HTML/Select/Common/Country.php');
require_once('I18N/IP2Country.php');
require_once('DB.php');
$dsn = "mysql://foo:bar@unix(/tmp/mysql.sock)/example";
$dbh = DB::connect($dsn, false);
$ip = new I18N_IP2Country($dbh, $_SERVER['REMOTE_ADDR']);
$ip->load();
$default = strtolower($ip->getTwoLetterCode());
$cs = new HTML_Select_Common_Country();
print $cs->toHTML('country', $default, 'Choose Country');
?>
This output is produced by code below:
USUSA
840
UNITED STATES
<?php
/* print remote users countrycodes and name */
require_once('I18N/IP2Country.php');
require_once('DB.php');
$dsn = "mysql://foo:bar@unix(/tmp/mysql.sock)/example";
$dbh = DB::connect($dsn, false);
$ip = new I18N_IP2Country($dbh, $_SERVER['REMOTE_ADDR']);
$ip->load();
print $ip->getTwoLetterCode() . "<br/>";
print $ip->getThreeLetterCode() . "<br/>";
print $ip->getNumber() . "<br/>";
print $ip->getCountry() . "<br/>";
?>
Installation
Get the latest IP-to-Country database create a following table (MySQL / SQLite example, your mileage may vary):
CREATE TABLE ip2country (
ipfrom INTEGER UNSIGNED,
ipto INTEGER UNSIGNED,
two CHAR(2),
three CHAR(3),
country VARCHAR(64)
);
MySQL
Import the database into you table with command:
LOAD DATA INFILE '/tmp/ip-to-country.csv'
INTO TABLE ip2country
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';
SQLite
For SQLite you firs need to convert the file with the following command:
sed 's/","/\t/g' < ip-to-country.csv | \
sed 's/"//g' > /tmp/ip-to-country2.csv
Then import with:
COPY ip2country FROM '/tmp/ip-to-country2.csv';
Flat CSV File
If you don’t have SQLite or any SQL database server access you still use the plain csv file downloaded. However using the class this way is the much slower than using it with SQL access. You have been warned.
Class itself
Last you must install the install the I18N_IP2Country class with PEAR commandline installer by issuing command:
pear install
http://www.appelsiini.net/download/I18N_IP2Country-0.3.0.tgz
Or upgrade with PEAR commandline installer by issuing command:
pear upgrade
http://www.appelsiini.net/download/I18N_IP2Country-0.3.0.tgz
Sorry, comments are closed for this article.