ip2location facebbook  ip2location twitter  ip2location google+ ip2location github

Importing IP2Location data into Redis and querying with PHP (IPv6)

The aim of this guide is to demonstrate how to import IP2Location data (DB11 IPv6) in csv form into Redis and then query the data in a PHP web page.

First of all, you will need to download the IP2Location DB11 IPv6 csv file.
Download Free LITE version at http://lite.ip2location.com/database/ip-country-region-city-latitude-longitude-zipcode-timezone
Download commercial version at http://ip2location.com/download?code=DB11CSVIPV6

Extract out the IPV6-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE.CSV file from the downloaded zipped file.

Important Note

We will not cover installation of Redis, Perl or PHP in this guide. We will assume you have already setup Redis on the localhost and are using PHP via Apache (also on the localhost). For this example, we are using a Debian Linux.

More info can be found at the following URLs if you need assistance with installations:
PHP: http://php.net/manual/en/install.unix.debian.php
Redis: http://redis.io/download
Perl Redis Library: http://search.cpan.org/~dams/Redis/lib/Redis.pm
PHP Redis Library: http://pecl.php.net/package/redis

We will be using the Perl Redis library to do mass import of CSV data into Redis and then querying the data via PHP using the PHP Redis library.

Importing the csv data into Redis

As mentioned earlier, we will be using a Perl script to perform the import of the CSV data into Redis as we need to format our CSV data into an easier to store form.

Create a new Perl file called importredis.pl and paste the following code into it:

use strict;
use Redis;

my $filename = 'IPV6-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE.CSV'; # IP2Location DB11 IPv6

my $data = '';
my $dbname = 'DB11IPV6';
my $client = Redis->new( server => 'localhost:6379', password => 'your_redis_password' );
$client->del($dbname);
open IN, "<$filename" or die;

my $counter = 0;
my $line = '';
while (<IN>)
{
	$line = $_;
	$line =~ s/[\r\n]+//; # remove EOL
	if ($line =~ /^"([^"]+)","[^"]+","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)"$/)
	{
		$counter++;
		my $ipfrom = $1;
		my $countrycode = $2;
		my $countryname = $3;
		my $statename = $4;
		my $cityname = $5;
		my $lat = $6;
		my $long = $7;
		my $zipcode = $8;
		my $timezone = $9;

		my $datastr = '"' . $ipfrom . "|" . $countrycode . "|" . $countryname . "|" . $statename . "|" . $cityname . "|" . $lat . "|" . $long . "|" . $zipcode . "|" . $timezone . '"';
		$datastr =~ s/([\@\%\$])/\\\1/g;
		$data .= ', ' . $ipfrom . ' => ' . $datastr;

		if ($counter % 5000 == 0)
		{
			print "Running line $counter\n";
			&runMe($data);
			$data = '';
		}
	}
}

if ($data ne '')
{
	&runMe($data);
	$data = '';
}
close IN;

sub runMe
{
	my $mydata = shift;
	eval('$client->zadd($dbname' . $mydata . ');');
	warn $@ if $@;
}

Run the Perl script by calling the below command in command prompt:
perl importredis.pl

Querying the IP2Location data from a PHP web page

Now, create a PHP file called test.php in your website.

Paste the following PHP code into it and then run it in the browser:

<?php
$ip = '2001:1388:b4b:342e:ad92:a9e7:bc5b:9340'; // test IPv6
// $ip = '::ffff:8.8.8.8'; // test IPv4 (must be in IPv4-Mapped IPv6 format)

function Dot2LongIP($ipv6) {
	$int = inet_pton($ipv6);
	$bits = 15;

	$ipv6long = 0;

	while($bits >= 0) {
		$bin = sprintf("%08b", (ord($int[$bits])));

		if($ipv6long) {
			$ipv6long = $bin . $ipv6long;
		}
		else {
			$ipv6long = $bin;
		}
		$bits--;
	}

	$ipv6long = gmp_strval(gmp_init($ipv6long, 2), 10);
	return $ipv6long;
}

function queryIP2Location($myip) {
	$redis = new Redis();
	$redis->connect('127.0.0.1'); // port 6379 by default
	if ($redis->auth('your_redis_password')) {
		$ipnum = Dot2LongIP($myip);

		$result = $redis->zRevRangeByLex('DB11IPV6', '['.$ipnum, '[0', 0, 1);
		$result = $result[0];
		$arr = explode("|", $result);

		echo "country code: " . $arr[1] . "<br>\n";
		echo "country name: " . $arr[2] . "<br>\n";
		echo "state name: " . $arr[3] . "<br>\n";
		echo "city name: " . $arr[4] . "<br>\n";
		echo "latitude: " . $arr[5] . "<br>\n";
		echo "longitude: " . $arr[6] . "<br>\n";
		echo "zip code: " . $arr[7] . "<br>\n";
		echo "time zone: " . $arr[8] . "<br>\n";
	}
	else {
		echo "Incorrect password\n";
	}
	$redis->close();
}

queryIP2Location($ip);
?>

Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.