jump to navigation

IP to Country component (Geo Location) March 29, 2006

Posted by rossoft in CakePHP.
trackback

1. Download and uncompress this to vendors/geoip/geoip.dat

2. Download this and copy to vendors/geoip/geoip.php

3. Download the CacheObject component

4. Copy this to app/controllers/components/geoip.php

<?php
/*
 * GeoIP component 
 * Detects the country of your visitor
 *
 * @author      RosSoft
 * @version     0.1
 * @license        MIT
 * 
 * @link http://www.maxmind.com/
 * 
 * DAT file:
 * @link http://www.maxmind.com/download/geoip/database/GeoIP.dat.gz
 * 
 * PHP INC file:
 * @link http://www.maxmind.com/download/geoip/api/php/geoip.inc
 */

class GeoipComponent extends Object
{
    var $components=array('cacheObject','session');
    
    function detect()
    {    
        $addr=env('REMOTE_ADDR');
        $cacheName='geoip/' . md5($addr);
        $sessionName='geoip';
        $this->session->del($sessionName);
        if ($this->session->check($sessionName))
        {
            $country=$this->session->read($sessionName);            
        }
        else
        {
            $country=$this->cacheObject->read($cacheName);
            if (!$country)
            {
                vendor('geoip/geoip');
                $geoip_data= geoip_open(VENDORS . 'geoip' . DS . 'geoip.dat',GEOIP_STANDARD); /* apertura y lectura del archivo utilizando la constante GEOIP_STANDARD como forma de lectura que adquiere valor en geoip.inc */
                $country=geoip_country_name_by_addr($geoip_data, $addr);
                geoip_close($geoip_data);
                
                $this->cacheObject->write($cacheName,$country,'+5 day');
            }
            $this->session->write($sessionName,$country);
        }
        return $country;        
    }
}
?>

Usage:

Include the component $var components=array(‘xx’,’geoip’);

In your controller:
$country=$this->geoip->detect();

The country is cached in session and in cache file.

Advertisements

Comments»

1. Martin - April 28, 2006

Nice class.

I’ve tried using the one that is at maxminds.com website.

2. Charbel - June 30, 2010

geopip.dat is no longer available, the link is broken, can up plz fix it or upload the file

3. charbel - February 4, 2011

why i should delete the session $this->session->del($sessionName);
??

Ahmad AlTwaijiry - November 16, 2011

Good question, why to delete the session !!?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: