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.
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:
load(); print $ip->getTwoLetterCode() . "<?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/>";
?>
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)
);
Import the database into you table with command:
LOAD DATA INFILE '/tmp/ip-to-country.csv' INTO TABLE ip2country FIELDS TERMINATED BY ',' ENCLOSED BY '"';
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';
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.
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.tgzOr upgrade with PEAR commandline installer by issuing command:
pear upgrade http://www.appelsiini.net/download/I18N_IP2Country-0.3.0.tgz TweetTagged with: Php