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.
Nice class.
I’ve tried using the one that is at maxminds.com website.
geopip.dat is no longer available, the link is broken, can up plz fix it or upload the file
why i should delete the session $this->session->del($sessionName);
??
Good question, why to delete the session !!?