Importing IP2Location data into CouchDB and querying with PHP

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

First of all, you will need to download the IP2Location DB26 CSV file.
Download commercial version at https://ip2location.com/download?code=DB26

Extract out the IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY-DISTRICT-ASN.CSV file from the downloaded zipped file.

Important Note

We will not cover installation of CouchDB or PHP in this guide. We will assume you have already setup CouchDB and 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
CouchDB: http://couchdb.apache.org/

Importing the CSV data into CouchDB

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

<?php
class CouchDB {
    private $username;
    private $password;
 
    function __construct($db, $host = 'localhost', $port = 5984, $username = null, $password = null) {
        $this->db = $db;
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
    }
 
    static function decode_json($str) {
        return json_decode($str);
    }
 
    static function encode_json($str) {
        return json_encode($str);
    }
 
    function create_db() {
        return $this->db_action('PUT');
    }
 
    function delete_db() {
        return $this->db_action('DELETE');
    }
 
    function import_db($data = NULL) {
        return $this->db_action('POST', $data);
    }
 
    function db_action($method = 'PUT', $data = NULL) {
        $url = '/' . $this->db . (($method == 'POST') ? '/_bulk_docs' : '');
        $request = new CouchDBRequest($this->host, $this->port, $url, $method, $data, $this->username, $this->password);
        return $request->send();
    }
 
    function db_query($ipnum) {
        $url = '/' . $this->db . '/_all_docs?include_docs=true&startkey="' . $ipnum . '"&limit=1';
        $request = new CouchDBRequest($this->host, $this->port, $url, 'GET', NULL, $this->username, $this->password);
        return $request->send();
    }
}
 
class CouchDBRequest {
    static $VALID_HTTP_METHODS = array('DELETE', 'GET', 'POST', 'PUT');
 
    private $method = 'GET';
    private $url = '';
    private $data = NULL;
    private $sock = NULL;
    private $username;
    private $password;
 
    function __construct($host, $port = 5984, $url, $method = 'GET', $data = NULL, $username = null, $password = null) {
        $method = strtoupper($method);
        $this->host = $host;
        $this->port = $port;
        $this->url = $url;
        $this->method = $method;
        $this->data = $data;
        $this->username = $username;
        $this->password = $password;
 
        if(!in_array($this->method, self::$VALID_HTTP_METHODS)) {
            throw new Exception('Invalid HTTP method: '.$this->method);
        }
    }
 
    function getRequest() {
        $req = "{$this->method} {$this->url} HTTP/1.0\r\nHost: {$this->host}\r\n";
 
        if($this->username || $this->password)
            $req .= 'Authorization: Basic '.base64_encode($this->username.':'.$this->password)."\r\n";
 
        if($this->data) {
            $req .= 'Content-Length: '.strlen($this->data)."\r\n";
            $req .= 'Content-Type: application/json'."\r\n\r\n";
            $req .= $this->data."\r\n";
        } else {
            $req .= "\r\n";
        }
 
        return $req;
    }
 
    private function connect() {
        $this->sock = @fsockopen($this->host, $this->port, $err_num, $err_string);
        if(!$this->sock) {
            throw new Exception('Could not open connection to '.$this->host.':'.$this->port.' ('.$err_string.')');
        }
    }
 
    private function disconnect() {
        fclose($this->sock);
        $this->sock = NULL;
    }
 
    private function execute() {
        fwrite($this->sock, $this->getRequest());
        $response = '';
        while(!feof($this->sock)) {
            $response .= fgets($this->sock);
        }
        $this->response = new CouchDBResponse($response);
        return $this->response;
    }
 
    function send() {
        $this->connect();
        $this->execute();
        $this->disconnect();
        return $this->response;
    }
 
    function getResponse() {
        return $this->response;
    }
}
 
class CouchDBResponse {
    private $raw_response = '';
    private $headers = '';
    private $body = '';
 
    function __construct($response = '') {
        $this->raw_response = $response;
        list($this->headers, $this->body) = explode("\r\n\r\n", $response);
    }
 
    function getRawResponse() {
        return $this->raw_response;
    }
 
    function getHeaders() {
        return $this->headers;
    }
 
    function getBody($decode_json = false) {
        return $decode_json ? CouchDB::decode_json($this->body) : $this->body;
    }
}
?>

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

<?php
require("couchdb.php");
 
$db = 'db26'; // must be all in lower case
$filename = 'IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY-DISTRICT-ASN.CSV';
$itemsperbatch = 5000;
$padzero = 10; // need to pad the ip numbers because key comparison is done as a string
 
$couchdb = new CouchDB($db, 'localhost', 5984, 'admin', 'YOUR_PASSWORD');
 
//delete old database
$result = $couchdb->delete_db();
 
//create database
$result = $couchdb->create_db();
 
//read data file
$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 $couchdb;
    global $counter;
    global $padzero;
 
    $mainarr = array();
    foreach ($dataarr as $data) {
        $data = rtrim($data); // clear EOL
 
        if (preg_match('/^"[^"]+","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)","([^"]+)"$/', $data, $matches) == 1) {
            $counter++;
            $ipto = $matches[1];
            $countrycode = $matches[2];
            $countryname = $matches[3];
            $regionname = $matches[4];
            $cityname = $matches[5];
            $latitude = $matches[6];
            $longitude = $matches[7];
            $zipcode = $matches[8];
            $timezone = $matches[9];
            $isp = $matches[10];
            $domain = $matches[11];
            $netspeed = $matches[12];
            $iddcode = $matches[13];
            $areacode = $matches[14];
            $weatherstationcode = $matches[15];
            $weatherstationname = $matches[16];
            $mcc = $matches[17];
            $mnc = $matches[18];
            $mobilebrand = $matches[19];
            $elevation = $matches[20];
            $usagetype = $matches[21];
            $addresstype = $matches[22];
            $category = $matches[23];
            $district = $matches[24];
            $asn = $matches[25];
            $as = $matches[26];
            
            $itemarr = array();
            $itemarr["_id"] = str_pad($ipto, $padzero, '0', STR_PAD_LEFT);
            $itemarr["COUNTRY_CODE"] = $countrycode;
            $itemarr["COUNTRY_NAME"] = $countryname;
            $itemarr["REGION_NAME"] = $regionname;
            $itemarr["CITY_NAME"] = $cityname;
            $itemarr["LATITUDE"] = $latitude;
            $itemarr["LONGITUDE"] = $longitude;
            $itemarr["ZIP_CODE"] = $zipcode;
            $itemarr["TIME_ZONE"] = $timezone;
            $itemarr["ISP"] = $isp;
            $itemarr["DOMAIN"] = $domain;
            $itemarr["NET_SPEED"] = $netspeed;
            $itemarr["IDD_CODE"] = $iddcode;
            $itemarr["AREA_CODE"] = $areacode;
            $itemarr["WEATHER_STATION_CODE"] = $weatherstationcode;
            $itemarr["WEATHER_STATION_NAME"] = $weatherstationname;
            $itemarr["MCC"] = $mcc;
            $itemarr["MNC"] = $mnc;
            $itemarr["MOBILE_BRAND"] = $mobilebrand;
            $itemarr["ELEVATION"] = $elevation;
            $itemarr["USAGE_TYPE"] = $usagetype;
            $itemarr["ADDRESS_TYPE"] = $addresstype;
            $itemarr["CATEGORY"] = $category;
            $itemarr["DISTRICT"] = $district;
            $itemarr["ASN"] = $asn;
            $itemarr["AS"] = $as;
            
            $mainarr[] = json_encode($itemarr);
        }
    }
 
    $jsonstr = '{"docs": [' . implode(',', $mainarr) . ']}';
    $result = $couchdb->import_db($jsonstr);
}
?>

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("couchdb.php");
 
$db = 'db26'; // must be all in lower case
 
// ip address to test
$ip = "8.8.8.8";
 
// need to pad the ip numbers because key comparison is done as a string
$padzero = 10;
 
$couchdb = new CouchDB($db, 'localhost', 5984, 'admin', 'YOUR_PASSWORD');
 
function queryIP2Location($myip) {
    global $couchdb;
    global $padzero;
 
    // convert IP address to IP number
    $ipnum = sprintf("%u", ip2long($myip));
    $ipnum = str_pad($ipnum, $padzero, '0', STR_PAD_LEFT);
 
    $result = $couchdb->db_query($ipnum);
    $resultarr = json_decode($result->getBody(), true);
    $resultarr = $resultarr["rows"][0]["doc"];
    return $resultarr;
}
 
$myresult = queryIP2Location($ip);
 
echo 'COUNTRY_CODE: ' . $myresult["COUNTRY_CODE"] . "<br>\n";
echo 'COUNTRY_NAME: ' . $myresult["COUNTRY_NAME"] . "<br>\n";
echo 'REGION_NAME: ' . $myresult["REGION_NAME"] . "<br>\n";
echo 'CITY_NAME: ' . $myresult["CITY_NAME"] . "<br>\n";
echo 'LATITUDE: ' . $myresult["LATITUDE"] . "<br>\n";
echo 'LONGITUDE: ' . $myresult["LONGITUDE"] . "<br>\n";
echo 'ZIP_CODE: ' . $myresult["ZIP_CODE"] . "<br>\n";
echo 'TIME_ZONE: ' . $myresult["TIME_ZONE"] . "<br>\n";
echo 'ISP: ' . $myresult["ISP"] . "<br>\n";
echo 'DOMAIN: ' . $myresult["DOMAIN"] . "<br>\n";
echo 'NET_SPEED: ' . $myresult["NET_SPEED"] . "<br>\n";
echo 'IDD_CODE: ' . $myresult["IDD_CODE"] . "<br>\n";
echo 'AREA_CODE: ' . $myresult["AREA_CODE"] . "<br>\n";
echo 'WEATHER_STATION_CODE: ' . $myresult["WEATHER_STATION_CODE"] . "<br>\n";
echo 'WEATHER_STATION_NAME: ' . $myresult["WEATHER_STATION_NAME"] . "<br>\n";
echo 'MCC: ' . $myresult["MCC"] . "<br>\n";
echo 'MNC: ' . $myresult["MNC"] . "<br>\n";
echo 'MOBILE_BRAND: ' . $myresult["MOBILE_BRAND"] . "<br>\n";
echo 'ELEVATION: ' . $myresult["ELEVATION"] . "<br>\n";
echo 'USAGE_TYPE: ' . $myresult["USAGE_TYPE"] . "<br>\n";
echo 'ADDRESS_TYPE: ' . $myresult["ADDRESS_TYPE"] . "<br>\n";
echo 'CATEGORY: ' . $myresult["CATEGORY"] . "<br>\n";
echo 'DISTRICT: ' . $myresult["DISTRICT"] . "<br>\n";
echo 'ASN: ' . $myresult["ASN"] . "<br>\n";
echo 'AS: ' . $myresult["AS"] . "<br>\n";
?>

Was this article helpful?

Related Articles