Pagodabox Tip : using GeoIP extension to get user’s location in Laravel

In one of the applications I’m building I needed to get user’s location (city) from their IP address.

One of the ways to go about this is to use some webservice that will convert the IP into geographical coordinates and then pass the result into your application.

Another way is to use geoip extension for PHP and get the user’s location(city) from the geoip extension. I was able to successfully use geoip extension to get user’s approximate location using free tools that now live on my Pagodabox instance.

The process of enabling GeoIP extension and using it in your Laravel application on Pagodabox is described below.

On Pagodabox list of extensions  you can see that geoip extension is included.

1) First, enable geoip in the boxfile:

    - geoip
    - curl
    - imagick
    - mbstring
    - pdo_mysql
    - mcrypt
    - gd
    - eaccelerator

2) Then, download the GeoLite database from Maxmind’s website:
Unpack it and place it into a folder within your application (for example in a folder called “GeoIP” in the root of your application )

3) Rename the database file to “GeoIPCity.dat”

4) In the Boxfile add “php_geoip_custom_directory” entry under your web1 configuration:

    - geoip
  php_geoip_custom_directory: /var/www/GeoIP

Alright, at this point your pagodabox instance will have GeoIP enabled and configured.

Now, to actually use it in your Laravel application, in a route or controller or model, use this code:

// check if geoip is loaded 
if (extension_loaded('geoip')) 
	// find user's location depending on IP and display it:
   	$geoip = geoip_record_by_name($_SERVER['HTTP_X_FORWARDED_FOR']);
   	if ($geoip) {
    	print_r($geoip, true);

At this point if you deploy your application and call this block of code you should see the output that will contain your location, city and other geo location.

Hope this is useful!

Enjoy tracking your users =)

You may also like

More in Code Blog
Bootstrap Button Generator

Last week I have made a nice addition to my Bootstrap Snippets site - . I have built and integrated...