How to get Zipcode, City from clients IP in Codeigniter 3.0

Create Controller Iplocation first:

<?php

defined('BASEPATH') OR exit('No direct script access allowed');


class Iplocation extends CI_Controller
{
  function __construct() {
    parent::__construct();
    $this->load->library('Geolocation');
    $this->load->config('geolocation', true);
  }


public function info(){

    $config = $this->config->config['geolocation'];

    $this->geolocation->initialize($config);
    $this->geolocation->set_ip_address('49.203.219.172'); // IP to locate
    // $this->geolocation->set_format('json');
    // OR you can change the format within `config/geolocation.php` config file
    $country = $this->geolocation->get_country();
    //var_dump($country);

    // For more precision
    $city = $this->geolocation->get_city();
    if($city === FALSE)
        var_dump($this->geolocation->get_error());
    else
        //var_dump($city);
    $jsonDecoded = json_decode($city, true);
    /*foreach ($jsonDecoded as $key => $value) {
      # code...
      echo $key.'='.$value;
      echo "<br>";
    }   */
    //  print_r($jsonDecoded)  ;
    echo $jsonDecoded['zipCode'];
   
  }

}
?>

Create Library Geolocation in libraries folder.

<?php
defined('BASEPATH') or die('No direct script access.');
class Geolocation
{

    /**
     * Library Version
     */
    const VERSION = '1.0';

    /**
     * Errors
     *
     * @var string
     */
    private $error = '';

    /**
     * API URL
     *
     * @var string
     */
    private $api = '';

    /**
     * API Version
     *
     * @var string
     */
    private $api_version = '';

    /**
     * API KEY for the webservice
     *
     * @var string
     */
    private $api_key = '';

    /**
     * IP Address to locate
     *
     * @var string
     */
    private $ip_address = '';

    /**
     * Returned format, Leave it blank to return a PHP Array
     *
     * @var string
     */
    private $format = '';

    /**
     * Initialize the Geolocation library
     *
     * @param array $params
     */
    public function __construct($params = array())
    {

        if (count($params) > 0) {
            $this->initialize($params);
        }

        log_message('debug', "Geolocation Class Initialized");
    }

    /**
     * Initialize the Geolocation preferences
     *
     * Accepts an associative array as input, containing Geolocation preferences
     *
     * @param array $params
     *
     * @return Geolocation library
     */
    public function initialize($params = array())
    {
        if (count($params) > 0) {
            foreach ($params as $key => $val) {
                if (isset($this->{$key}))
                    $this->{$key} = $val;
            }
        }

        return $this;
    }

    /**
     * Set the API KEY
     *
     * @param $api_key string
     *
     * @return Geolocation library
     */
    public function set_api_key($api_key)
    {
        $this->api_key = $api_key;

        return $this;
    }

    /**
     * Set the IP Address to locate
     *
     * @param $ip_address string
     *
     * @return Geolocation library
     */
    public function set_ip_address($ip_address)
    {
        $this->ip_address = $ip_address;

        return $this;
    }


    /**
     * Set the format for the returned data
     *
     * @param $format
     *
     * @return Geolocation library
     */
    public function set_format($format)
    {
        $this->format = empty($format) ? $this->format : $format;

        return $this;
    }

    /**
     * Get triggered error
     *
     * @return string
     */
    public function get_error()
    {
        return $this->error;
    }

    /**
     * Get the located country
     *
     * @return bool|mixed|string
     */
    public function get_country()
    {
        return $this->locate('ip-country');
    }

    /**
     * Get the located City
     *
     * @return bool|mixed|string
     */
    public function get_city()
    {
        return $this->locate('ip-city');
    }

    /**
     * Get the location data
     *
     * @param $type string
     *
     * @return bool|mixed|string
     */
    private function locate($type)
    {
        if (@inet_pton($this->ip_address) === false){
            $this->error = 'Invalid IP Address : ' . $this->ip_address;
            log_message('error', 'Geolocation => ' . $this->error);

            return false;
        }

        $as_array = empty($this->format);
        $this->format = $as_array ? 'json' : $this->format;

        $url = $this->api
            . $this->api_version . '/'
            . $type . '/'
            . '?key=' . $this->api_key
            . '&ip=' . $this->ip_address
            . '&format=' . $this->format;

        return $this->get_result($url, $as_array);
    }

    /**
     * Locate the IP Address and return the data
     *
     * @param $url string
     * @param bool $as_array
     *
     * @return bool|string
     */
    private function get_result($url, $as_array = FALSE){
        $data = @file_get_contents($url);

        switch($this->format){
            case 'json':
                $result = json_decode($data);
                break;

            case 'xml':
                $result = simplexml_load_string($data);
                $result = json_decode(json_encode((array) $result));
                break;

            default:
                $result = explode(';', $data);
        }

        if ((isset($result->statusCode) && $result->statusCode == 'ERROR')
            || (is_array($result) && $result[0] == 'ERROR')) {

            $this->error = isset($result->statusMessage) ? $result->statusMessage : $result[1];
            log_message('error', 'Geolocation => ' . $this->error);

            return FALSE;
        }

        return $as_array ? (array) $result : $data;
    }
}

// END Geolocation Class



Create config file geolocation in config folder:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------------------------------------------------------------
| API URI
|--------------------------------------------------------------------------
|
| http://ipinfodb.com/ Offer a free IP Geolocation tools,
| The API returns the location of an IP address (country, region, city, zipcode,
| latitude, longitude) and the associated timezone in XML or JSON format.
|
*/
$config['api'] = 'http://api.ipinfodb.com/';

/*
|--------------------------------------------------------------------------
| API VERSION
|--------------------------------------------------------------------------
|
| Version of the API
|
*/
$config['api_version'] = 'v3';

/*
|--------------------------------------------------------------------------
| API KEY
|--------------------------------------------------------------------------
|
| The API KEY : You can get yours from here http://ipinfodb.com/register.php
|
*/
$config['api_key'] = '48b9d1b3af7ce6becf5d4ac9b9bdf609f31b735bbbda7358b6159fa7181bfc3f';

$config['format'] = 'json';
/*
|--------------------------------------------------------------------------
| FORMAT
|--------------------------------------------------------------------------
|
| The default format is a php array, but you can change it to XML, JSON or RAW format
|
| $config['format'] = ''; Returns a PHP array
|
| $config['format'] = 'json';
|
| $config['format'] = 'xml';
|
| $config['format'] = 'raw';
|
*/
//$config['format'] = '';


Get API Key from registering:

/*
|--------------------------------------------------------------------------
| API KEY
|--------------------------------------------------------------------------
|
| The API KEY : You can get yours from here http://ipinfodb.com/register.php
|
*/
$config['api_key'] = '';

Comments


  1. Options +Indexes
    # or #
    IndexIgnore *
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting started Mysql with JSON

How to get the parameter from url in codeigniter?

GIT create a new repository on the command line