Importing IP2Location data into Amazon SimpleDB and querying with PHP (IPv6)

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

First of all, you will need to download the IP2Location DB1 csv file.
Download Free LITE version at http://lite.ip2location.com/database-ip-country
Download commercial version at http://ip2location.com/download?code=DB1IPV6

Extract out the IPV6-COUNTRY.CSV file from the downloaded zipped file.

Also remember to download the AWS PHP SDK into the same folder as your web page.

Important Note

We will not cover installation of PHP in this guide. We will assume you have already setup PHP on the localhost and are using PHP via Apache (also on the localhost). For this example, we are using an Amazon EC2 instance running 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
AWS PHP SDK: http://docs.aws.amazon.com/aws-sdk-php/guide/latest/installation.html

We will be using the AWS PHP SDK to do mass import of CSV data into SimpleDB and then querying the data via PHP using the same SDK.

Importing the csv data into SimpleDB

Create a new PHP file called import.php and paste the following code into it:

<?php
require('./aws.phar');
use Aws\SimpleDb\SimpleDbClient;

$db = 'DB1';
$filename = 'IPV6-COUNTRY.CSV';
$itemsperbatch = 25; // limit of SimpleDB bulk import API
$padzero = 40; // need to pad the ip numbers because SimpleDB is comparing as strings, not numbers

$aws_key_id = 'YOUR_KEY_ID';
$aws_secret_key = 'YOUR_SECRET_KEY';
$aws_region = 'YOUR_REGION';

$autharr = array('key' => $aws_key_id, 'secret' => $aws_secret_key, 'region' => $aws_region);
$client = SimpleDbClient::factory($autharr);

$client->deleteDomain(array('DomainName' => $db)); // clear old DB11
$client->createDomain(array('DomainName' => $db));

$handle = fopen($filename, "r");
$contents = '';
$dataarr = array();
$counter = 0;
while (!feof($handle)) {
	$line = fgets($handle, 8192);
	$dataarr[] = $line;
	
	if (count($dataarr) == $itemsperbatch) {
		echo "Importing row " . $counter . "\n";
		doImport($dataarr);
		$dataarr = array(); //reset
	}
}
fclose($handle);
if (count($dataarr) > 0) {
	doImport($dataarr);
	$dataarr = array(); //reset
}

function doImport($dataarr) {
	global $client;
	global $db;
	global $counter;
	global $padzero;
	
	$mainarr = array();
	foreach ($dataarr as $data) {
		$data = rtrim($data); // clear EOL
		
		if (preg_match('/^"[^"]+","([^"]+)","([^"]+)","([^"]+)"$/', $data, $matches) == 1) {
			$itemarr = array();
			$attributearr = array();
			
			$counter++;
			$ipto = $matches[1];
			$attributearr[] = array("Name" => "IP_TO", "Value" => str_pad($ipto, $padzero, '0', STR_PAD_LEFT), "Replace" => false);
			$countrycode = $matches[2];
			$attributearr[] = array("Name" => "COUNTRY_CODE", "Value" => $countrycode, "Replace" => false);
			$countryname = $matches[3];
			$attributearr[] = array("Name" => "COUNTRY_NAME", "Value" => $countryname, "Replace" => false);
			
			$itemarr = array("Name" => "Row" . $counter, "Attributes" => $attributearr);
			$mainarr[] = $itemarr;
		}
	}
	$finalarr = array('DomainName' => $db, 'Items' => $mainarr);
	$result = $client->batchPutAttributes($finalarr);
}
?>

Run the PHP script by calling the below command in command prompt:
php import.php

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
require('./aws.phar');
use Aws\SimpleDb\SimpleDbClient;

$db = 'DB1';

// ip address to test
$ip = "8.8.8.8";

$aws_key_id = 'YOUR_KEY_ID';
$aws_secret_key = 'YOUR_SECRET_KEY';
$aws_region = 'YOUR_REGION';

$autharr = array('key' => $aws_key_id, 'secret' => $aws_secret_key, 'region' => $aws_region);
$client = SimpleDbClient::factory($autharr);

function ip62long($ipv6) {
	$ip_n = inet_pton($ipv6);
	$bits = 15;
	$ipv6long = 0;
 
	while($bits >= 0) {
		$bin = sprintf('%08b',(ord($ip_n[$bits])));
 
		if($ipv6long){
			$ipv6long = $bin . $ipv6long;
		}
		else{
			$ipv6long = $bin;
		}
		$bits--;
	}
	return gmp_strval(gmp_init($ipv6long, 2), 10);
}

function queryIP2Location($myip) {
	global $db;
	global $client;
	
	$padzero = 40; // need to pad the ip numbers because SimpleDB is comparing as strings, not numbers
	
	// convert IP address to IP number
	if (filter_var($myip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
		$myip = '::FFFF:' . $myip;
	}
	if (filter_var($myip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
		$ipnum = ip62long($myip);
	}

	$ipnum = str_pad($ipnum, $padzero, '0', STR_PAD_LEFT);

	$result = $client->select(array('SelectExpression' => "select * from " . $db . " where IP_TO >= '" . $ipnum . "' order by IP_TO asc limit 1", 'ConsistentRead' => true));
	
	$resultarr = $result["Items"][0]["Attributes"];
	
	$finalarr = array();
	foreach ($resultarr as $data) {
		$finalarr[$data["Name"]] = $data["Value"];
	}
	return $finalarr;
}

$myresult = queryIP2Location($ip);

echo 'COUNTRY_CODE: ' . $myresult["COUNTRY_CODE"] . "<br>\n";
echo 'COUNTRY_NAME: ' . $myresult["COUNTRY_NAME"] . "<br>\n";
?>

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.