Strict Standards: Redefining already defined constructor for class Object in /home/dizz/cake_1.2.5/cake/libs/object.php on line 63

Strict Standards: Non-static method Configure::getInstance() should not be called statically in /home/dizz/cake_1.2.5/cake/bootstrap.php on line 47
CakePHP Geotargeting Helper |

CakePHP Geotargeting Helper



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"?>
<CountryName>United States</CountryName>
<City>Mountain View</City>


  • 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.


class GeoIpHelper extends Helper {

public $url;
public $ip;

public function __construct () {

$this->url = "{$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();
$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


kettle said on January 7th 2010, 9:54am
Awesome, looking forward to trying this out. After a cursory look, I have just one small suggestion; in your constructor, you might want to use the following to retrieve the user's IP address instead to get around ISP proxies:

$ip = ( env('HTTP_X_FORWARDED_FOR') ? env('HTTP_X_FORWARDED_FOR') : env('REMOTE_ADDR') );
Moz said on January 8th 2010, 2:03am
Great post Andrew.

Kettle is quite correct about using the above snippet of code. This also gets around issues with servers that use load balancing.

Thanks again.
spnkychnk said on March 11th 2010, 1:58am
It is not working i am not getting any info.even the ip info is wrong. please help
Claudio said on July 11th 2011, 12:00pm
Very good. How can I call the function get_city in my view?
Would it be "echo $geoIp->get_city();" ?
Thank you.
Add New Comment