Yii 1.1: geoip

Net_GeoIP port for Yii - Get a geographical location given an IP address
19 followers

This extension is a port of the Net_GeoIP PEAR package for Yii to get a geographical location given an IP address.

Made some adjustments to make it independent of the PEAR package. Basically it's just a proxy module that uses the library developed ported by Hans Lellelid in the PEAR package.

Resources

Documentation

Requirements

  • Yii 1.0 or above (tested with Yii 1.1.3 but should work with previous versions)

Installation

  • Extract the release file under protected/extensions
  • Change main.php configuration file
'components' => array(
      ...
      'geoip' => array(
          'class' => 'application.extensions.geoip.CGeoIP',
          // specify filename location for the corresponding database
          'filename' => 'C:\path\to\GeoIP\GeoLiteCity.dat',
          // Choose MEMORY_CACHE or STANDARD mode
          'mode' => 'STANDARD',
      ),
      ...
  ),

Usage

See the following code example:

$location = Yii::app()->geoip->lookupLocation();
  // with IP in google.com
  $location = Yii::app()->geoip->lookupLocation('209.85.135.104');
  $countryCode = Yii::app()->geoip->lookupCountryCode();
  $countryName = Yii::app()->geoip->lookupCountryName();
  $org = Yii::app()->geoip->lookupOrg();
  $regionCode = Yii::app()->geoip->lookupRegion();
 
  // Location attributes:
  $location->countryCode
  $location->countryCode3
  $location->countryName
  $location->region
  $location->regionName
  $location->city
  $location->postalCode
  $location->latitude
  $location->longitude
  $location->areaCode
  $location->dmaCode

Notes:

Methods lookupOrg and lookupRegion require specific databases (only paid versions available from MaxMind).

Change Log

June 1, 2013

  • Fix usage of non-static method in static context

July 21, 2010

  • Initial release.

Total 2 comments

#15190 report it
seniorboss at 2013/10/16 05:17am
Caching

Hi, can you post where you've modified the code? Thank you

#2630 report it
Sarke at 2011/01/24 06:05am
Easy and fast.

Works great, thanks!

I found that the "MEMORY_CACHE" was not a good idea as it loads the entire database into memory, and it is then destroyed after the script ends. So it's really much slower and a lot more memory consuming (35MB instead of 5MB).

Instead, I am using a little caching as follows:

$ip = CHttpRequest::getUserHostAddress();
$handle = 'GeoIP:'.$ip;
 
$data = Yii::app()->cache->get($handle);
if ($data === false)
{
    $location = Yii::app()->geoip->lookupLocation($ip);
 
    $data = array(
        'ip' => $ip,
        'country' => $location ->countryCode3,
        'countryName' => $location ->countryName,
        'region' => $location ->region,
        'regionName' => $location ->regionName,
        'city' => $location ->city,
    );
 
    Yii::app()->cache->set($handle, $data, 3600);
}

Leave a comment

Please to leave your comment.

Create extension