CakePHP Geotargeting Helper
Introduction
This helper utilizes IPInfoDB's geolocation tools to find out geographical information from an IP address. The helper also caches results from the webservice per IP address.
You can take a look at IPInfoDB API documentation here.
Here is an example response from the webservice:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>06</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipPostalCode>94043</ZipPostalCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.057</Longitude>
<Timezone>-8</Timezone>
<Gmtoffset>-8</Gmtoffset>
<Dstoffset>-7</Dstoffset>
</Response>
Requirements
- CakePHP 1.2+
How to Use
Place the helper inside of your CakePHP applications helper folder and then include it in the controllers you need. I have implemented 3 helper methods to get the city, state and zip code that you can use as examples to build your own methods or you can grab the entire array from the get_response method.
Code
<?php
class GeoIpHelper extends Helper {
public $url;
public $ip;
public function __construct () {
parent::__construct();
$ip = $_SERVER['REMOTE_ADDR'];
$this->url = "http://ipinfodb.com/ip_query.php?ip={$ip}";
$this->ip = $ip;
}
public function get_response () {
if (!$response = Cache::read('geoip' . r('.', '_', $this->ip))) {
App::import('Core', array('HttpSocket', 'Xml'));
$socket = new HttpSocket();
$socket->get($this->url);
$xml = new Xml($socket->response['body']);
$response = $xml->toArray();
Cache::write('geoip' . r('.', '_', $this->ip), $response, '+1 month');
}
return $response;
}
public function get_city () {
$response = $this->get_response();
return $response['Response']['City'];
}
public function get_state () {
$response = $this->get_response();
return $response['Response']['RegionName'];
}
public function get_zip () {
$response = $this->get_response();
return $response['Response']['ZipPostalCode'];
}
}
If you have any questions or comments drop me a line below and I will try to get back to you as soon as possible.
Last Updated: January 7th 2010, 6:15am
Download: CakePHP Geotargeting Helper


4 Comments
$ip = ( env('HTTP_X_FORWARDED_FOR') ? env('HTTP_X_FORWARDED_FOR') : env('REMOTE_ADDR') );
Kettle is quite correct about using the above snippet of code. This also gets around issues with servers that use load balancing.
Thanks again.
Would it be "echo $geoIp->get_city();" ?
Thank you.