PHP Classes

PHP Tutorial to Detect User Location from the IP address With IP2Location Geolocation

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Tutorial to Detec...   Post a comment Post a comment   See comments See comments (19)   Trackbacks (0)  

Author:

Viewers: 1,482

Last month viewers: 80

Categories: PHP Tutorials, Sponsored

Sometimes it is necessary to determine the user geographic location for instance to serve more appropriate content. One way to do it is to determine the location associated to the IP address of his computer. IP2Location provides a free solution for this using the IP2Location Lite database.

Read this article to learn how to detect the user location using the IP2Location Lite database service.




Loaded Article

Contents

Why Would You Need to Detect the User Location from the IP Address?

Installation

IP Database Setup

Code Example

Testing

Conclusion

IP2Location logo

Why Would You Need to Detect the User Location from the IP Address?

IP geolocation detection is used in many projects for instance to detect from which country a user has come from. Why is it important?

Firstly, it helps to build better localization for the Web site guests, i.e. adapt the site depending on the user location, thus making them more happy and loyal.

When you know the country of the user, you can, for example, switch the user interface messages to their language. If a visitor is from England, it makes sense to switch the language to English. Users like it when a site is made convenient, and it is not necessary to dig in the page in order to find the language switcher when it exists.

Also your application can show the prices based on the user's local currency. Visit for instance the Momondo.com Web site. It helps to search for cheap airline tickets. Once your country is detected, the Web site will automatically switch to your local language and your local currency. It is convenient.

Momondo localization

Second, country detection helps to improve the safety and security of the users. If you visit Gmail from home in your own country, and you can see there is someone who accessed your account using your username and password from another country far-far away, then it is possible that your account has been hacked.

So does Facebook. For example, once I flew from Ukraine to Denmark, and Facebook did not like that I accessed my account in the morning in one country, and a few hours later I got to Facebook from another distant country in the evening. Facebook became suspicious and asked me to confirm my password.

As you can see, this technique is used in any modern project. It is very simple to do, so let's see the details.

Installation

There are several ways to interact with IP database: you could grab a CSV file of the IPs and geo-data, or import it in the database and run SQL queries. In this article we will see how to build an app even without a database, we will access a IP database in the form of a binary file which might be handy on many hosting environments.

Although the IP2Location full database version is paid, you can download a free version that is still very useful.

The installation process is described here. But there were a couple issues with it, so read carefully to overcome the obstacles.

We need to create a new folder in your local Web server document root, for example, 'ip2loc'. Also create a sub-folder inside called 'db'. Here we will place the binary file of the database.

Then, as your are in the 'ip2loc' folder, create a file called "composer.json" with this contents:

{
 "require": {
  "ip2location/ip2location-php": "7.*"
 }
}

If you are not familiar with composer, it is a dependencies manager that takes responsibility to download all the libraries your application needs. This is how to install Composer.

The file above tells to the composer that PHP implementation for ip2location library should be downloaded and made available to our app.

Then you need to run this command to download that library:

composer install --prefer-source

IP Database Setup

First thing you need to do is to visit IP2Location LITE DB11 page, click "Download IPv4 BIN" and then register for a free download account. After that you will download a 30MB ZIP file. Great! Unzip it to ip2loc/db folder.

What you'll get there is a folder called "IP2LOCATION-LITE-DB11.BIN" that contains a database binary file "IP2LOCATION-LITE-DB11.BIN" and a couple of support text files.

If you work on a Mac like I do (or any kind of Linux), you need to run these 2 commands to make your database folder and file readable. Without it you will get an error message from PHP that the bin file is not there:

chmod a+X db/IP2LOCATION-LITE-DB11.BIN/
chmod -R a+r db/IP2LOCATION-LITE-DB11.BIN/

Code Example

Then paste this code to test your installation:

<?php

 require 'vendor/autoload.php';

 $db = new \IP2Location\Database( 'db/IP2LOCATION-LITE-DB11.BIN/IP2LOCATION-LITE-DB11.BIN', \IP2Location\Database::FILE_IO);

 $records = $db->lookup('8.8.8.8', \IP2Location\Database::ALL);

 echo '<pre>';
 echo 'IP Number             : ' . $records['ipNumber'] . "\n";
 echo 'IP Version            : ' . $records['ipVersion'] . "\n";
 echo 'IP Address            : ' . $records['ipAddress'] . "\n";
 echo 'Country Code          : ' . $records['countryCode'] . "\n";
 echo 'Country Name          : ' . $records['countryName'] . "\n";
 echo 'Region Name           : ' . $records['regionName'] . "\n";
 echo 'City Name             : ' . $records['cityName'] . "\n";
 echo 'Latitude              : ' . $records['latitude'] . "\n";
 echo 'Longitude             : ' . $records['longitude'] . "\n";
 echo 'Area Code             : ' . $records['areaCode'] . "\n";
 echo 'IDD Code              : ' . $records['iddCode'] . "\n";
 echo 'Weather Station Code  : ' . $records['weatherStationCode'] . "\n";
 echo 'Weather Station Name  : ' . $records['weatherStationName'] . "\n";
 echo 'MCC                   : ' . $records['mcc'] . "\n";
 echo 'MNC                   : ' . $records['mnc'] . "\n";
 echo 'Mobile Carrier        : ' . $records['mobileCarrierName'] . "\n";
 echo 'Usage Type            : ' . $records['usageType'] . "\n";
 echo 'Elevation             : ' . $records['elevation'] . "\n";
 echo 'Net Speed             : ' . $records['netSpeed'] . "\n";
 echo 'Time Zone             : ' . $records['timeZone'] . "\n";
 echo 'ZIP Code              : ' . $records['zipCode'] . "\n";
 echo 'Domain Name           : ' . $records['domainName'] . "\n";
 echo 'ISP Name              : ' . $records['isp'] . "\n";
 echo '</pre>';

You can get the country code, country name, region name, city name, latitude, longitude, ZIP code and time zone in the IP2Location LITE DB11.

All data below coordinates is available only in the paid version, but even with the free version the data is pretty valuable.

Testing

Let's test if this solution can detect where you are, i.e. your own public IP address.

There is a very easy way to find out your IP address: just search in Google for my IP and copy the IP address from Google results page.

Then you can paste it in the code instead of the default "8.8.8.8" and check if it shows your country, just edit this line:

$records =  $db->lookup('8.8.8.8', \IP2Location\Database::ALL);

In a real-world application you would use the country-specific data (language and currency) to change localization of your application, or check if the user accesses the site from the same country as last time:

if ('UA' == $records['countryCode']) {
    $language = 'Ukrainian';
    $currency = 'Hryvna';
    $currencyCode = 'hrn.';
}
else {
    $language = 'English';
    $currency = 'Euro';
    $currencyCode = '€';
}

Please do not test the script using local private IP address in LAN. You will always get “-” in the country code because it is a reserved IP address range.

Conclusion

IP2Location IP database service is very useful. There is a free version that you can use to detect the user country but if you need more accuracy or more details other than the region, city, zip code, latitude, longitude, etc., you can upgrade to a paid version.

There is an alternative form of using the IP2Location service which is based on Web services. That will be covered in the next part of this article.

If you liked this article or have questions regarding the use of the IP2Location service, post a comment here.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

3. Beware of false data - PHP-4-Business (2015-12-28 18:45)
Do not use IP geolocation for City, or latitude, etc.... - 8 replies
Read the whole comment and replies

1. quick start - Andrei (2015-12-28 00:55)
nice article for quick start!... - 5 replies
Read the whole comment and replies

2. mySQL version? - Robert (2015-12-28 00:54)
mySQL version?... - 3 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Tutorial to Detec...   Post a comment Post a comment   See comments See comments (19)   Trackbacks (0)