How to detect user location based in IP address

By Admin
PHP
25 Jul 2022

Psst: this my first english article, sorry for bad english.

This time I want to share about how to detect user location based on it IP address. We will use IP2Location Geolocation database and IP2Location Geolocation PHP client. So why we need to detect user location when it access our website and why it maybe important for you?

First, with knowing user location, you can maximize your website, so user can feel more helpful & happy when visit your site. For example when you know where is user country, you can automatically switch your language based on it country. For example if the user from Singapore you can switch the language to English, but when the user from Indonesia you can switch the language to Bahasa and also other country.  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.Beside that you also can make the site automatically change its currency based on user country. So the user doesn’t need to find a button to select their local currency.

Second, you can improve the security of your website. Have you travel to another country and login to your facebook account? Do you receive some notification that someone try to login to your account from x country for example? If yes, that means the system using location based service to track your location. So when you login from new place, the system ask you if that really you or not. Facebook became suspicious because that not the country where you are usually used to login. 

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

Like I said before, we need IP2Location database and PHP client first. Although the IP2Location full database version is paid, you can download a free version that is still very useful but you need to register to download the database. We also use composer to download its dependency. So if you don’t know what is composer, you can google it or visit my article: 

First, 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.*"
	 }
}

After that, you need to run composer install --prefer-source from your terminal and wait a moment. Let composer install it for you. 

So now you have the package installed and IP2Location database down. Let start to next step.

Database Setup

Unzip the database file 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) and get some permission error, 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/

So your database is ready now. Next is start to code.

Example Code

So the plan is check where is your location using your public ip address. Let’s get our hand dirty a bit. First make a index.php and put some code like below:

<?php
include 'vendor/autoload.php';

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

$your_public_ip = '8.8.8.8';

$records = $db->lookup($your_public_ip, IP2LocationDatabase::ALL);

 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"; 

So that is, so simple right? Now lets try the result in your browser.

As you can see, the country for public ip address : 8.8.8.8  is United State, so if you want the website change the site language, that must be english right? As you see, some parameter may be unavailable because we only use lite version. If you need more feature, you can upgrade it.

In example I’m using 8.8.8.8 as public ip, so how to know your location right now by your public ip address? Lets make some modify of the index.php file  or you can just change the value of $public_ip_address to your public ip. You can check your public ip here or just modify index.php like below.

<?php include 'vendor/autoload.php';

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

$external_content = file_get_contents('<a href="http://checkip.dyndns.com/')"-->http://checkip.dyndns.com/');
preg_match('/Current IP Address: [?([:.0-9a-fA-F]+)]?/', $external_content, $m);
$your_public_ip = $m[1];

$records = $db->lookup($your_public_ip, IP2LocationDatabase::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 '

‘;

Because we are in local server, we need to specify our public address. But when it come to your production website, maybe you can change the public id address by $_SERVER['REMOTE_ADDR'] or if your user behind proxy, you can use $_SERVER['HTTP_X_FORWARDED_FOR'] but it really easy to spoofed.

Conclusion

Now you can easily find user location by their public ip address. With that you can make some automation for your website like select language and currency based on user location. 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.

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

Artikel Lainnya

Artikel lain yang mungkin menarik juga untuk kamu baca.

Belajar PHP – Apa Itu Interface Dalam PHP?

Pada tutorial belajar PHP kali ini, kita akan membahas tentang yang namanya Interface dalam PHP. Apa itu interface?
Admin
5 min read

Pengertian PHP, Fungsi dan contohnya.

Halo teman ngide, kali ini kita akan membahas apa itu php, sejarah PHP. fungsi PHP secara umum dan juga istilah lainya yang berkaitan dengan PHP.
Admin
5 min read

Cara menginstall XAMPP di windows

Jika kamu ingin membuat website di komputer pribadi kamu, maka kamu membutuhkan sebuah web server. Nah salah satu aplikasi untuk membuat web server di komputer kamu adalah XAMPP.
Admin
5 min read

© 2024