PHP Classes

PHP Tutorial to Detect User Location by IP address With IP2Location Web Service

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 (8)   Trackbacks (0)  

Author:

Viewers: 5,378

Last month viewers: 19

Categories: PHP Tutorials, Sponsored

IP2Location provides a free LITE database to find the location of Web site users given their computer IP address. However, this requires that the database be installed on the Web site server and be updated regularly.

An alternative is to access a Web service provided by IP2Location to obtain the same geolocation information always up to date without need to install any database in the local server.

Read this article to learn how to use the IP2Location GeoLocation Web service.




Loaded Article

Contents

Introduction

PHP Command Line

What is a Web Service?

Forming URL to Call the Web Service

Making the Web Service Call

Conclusion


Introduction

I am writing this article from Borispol airport which is close to Kiev city (Ukraine). Let's use this example to check how easy is the IP2Location Web service that helps to detect geo location just by the given IP address.

I don't have any database or IP2Location binary file installed on my laptop that I could query, and I want to check if my current IP address can be converted to a location.

To cut the long story short, it can be done with PHP one-liner (one line of code that solves the task) if we just query IP2Location Web service. The Web service access has a paid version, but even the free demo version is enough to play with this solution.

PHP Command Line

There is an easy way to run single PHP commands from command line: you just need to run PHP interpreter with "-r" flag like this:

php -r 'echo "Hello world";'

This will output "Hello world" of course.

So in our example we are going to use this approach to make the calls to the Web service.

What is a Web Service?

In short, a Web service is a URL you call with a list of parameters and get results back, usually in a format like XML or JSON. The service can be currency exchange rate for a given date and currency, or, as in our example, you can send an IP address as text and get the location information.

The advantage of this approach is that there is no need to install anything or access any kind of a local file or database. It is web based. You are just ready to go.

Another advantage of the Web service comes from its nature. It can potentially be used not only on server-side with help of PHP, but also at client-side by JavaScript.

Since the Web service call can return the response in the JSON format, which is native JavaScript notation, it's not so hard to make a call and process the result. The only thing to care about is when you send cross-domain AJAX requests you maybe restricted if you do not send the right set of CORS headers from the server.

The obvious limitation of the Web service approach is the request speed. Although it works pretty fast, it's slower than accessing a local binary file or a local database due to the network latency overhead.

Anyway, we are talking about "1 second of waiting time" in case of a web-service versus "less than 1 second waiting time" in case of local storage access, which is not a mission-critical constraint in many cases.

All in all, it is good to know, that there is an easy, fast and cheap way to start using the IP address to location conversion with help of a Web service.

Technically, it takes 2 small steps to make a request to the Web service:

  1. Form a URL address with parameters.
  2. Make a call, e.g. with help for instance of the file_get_contents() function, to query the remote Web service URL and get its response in some text format (XML or JSON)

Forming URL to Call the Web Service

In the first step, we need to combine the Web service address, called an endpoint, with the actual parameters of the conversion. The endpoint can be checked in the manual reference. It is just: http://api.ip2location.com/ .

There are many different parameters. You can find the complete list in the Web service documentation. We need just these:

  • ip = ... — the IP address we are converting to a location
  • key = demo We have to use this to get access to the demo version of the Web service
  • package = WS10 — The package to query. Differrent packages return different lists of results. The WS10 is pretty advanced package and returns lots of data for the given IP like the geo location, the geographic coordinates, the ZIP code, ISP and its domain name
  • format = json How to format the results so it is easier for our code to process it. I prefer JSON format since it is a piece of cake to convert it to a plain PHP array.

The only variable value here is the IP address. You can find it in your network settings, or just visit http://ipaddress.my for “my IP address” information.

My IP address is "77.52.107.69".

So we add the parameters to the endpoint with "?" as separator between the endpoint and parameters list, and "&" as seperator between the parameters. The final URL to request is this:

http://api.ip2location.com/?ip=77.52.107.69 &key=demo &package=WS10 &format=json

Making the Web Service Call

Now let's try it in action. If you run this in the command line, you will get the raw JSON response:

php -r "echo file_get_contents( 'http://api.ip2location.com/?'. 'ip=77.52.107.69&key=demo' . '&package=WS10&format=json');"

ip2location one-liner

We want to change a couple of things: Convert it from raw JSON to PHP array, and then display this array. That is why we wrap our call into json_decode() function, and replace "echo" with "print_r" to display the resulting array.

php -r "print_r( json_decode( file_get_contents( 'http://api.ip2location.com/?' . 'ip=77.52.107.69&key=demo' . '&package=WS10&format=json', true )));"

The output looks like this:

 [country_code] => UA
 [country_name] => Ukraine
 [region_name] => Kyyivs'ka Oblast
 [city_name] => Boryspil
 [latitude] => 50.35269
 [longitude] => 30.95501
 [zip_code] => 08315
 [isp] => CJSC Ukrainian Mobile Communications
 [domain] => mts.com.ua

It means that the city_name is "Boryspil" and it is placed in "Kyyivs'ka Oblast" region in Ukraine. The latitude and longitude are the coordinates of Boryspil, not the exact coordinates of any user with the IP address.

If you want a traditional PHP script, it would look like this:

<?php
 // the IP address is unknown, so it equals to "%s" now.
 $urlTemplate = 'http://api.ip2location.com/?' . 'ip=%s&key=demo' .  '&package=WS10&format=json';
    
 $ipAddress = '77.52.107.69'; // can come from GET request, database, whatever

 // replace the "%s" in template with real IP address
 $urlToCall = sprintf( $urlTemplate, $ipAddress);

 $rawJson = file_get_contents( $urlToCall );

 $geoLocation = json_decode( $rawJson, true );

 echo 'Hello to ', $geoLocation['city_name'];

Conclusion

Well that is it. As you can see, it took us one line of code to use the IP2Location Web service or a very short script for a dynamic solution.

Despite it is not as fast as it can be the solution based on a local geolocation database file, it does not require any software installation to use the IP2Location Web service.

If you liked this article or you have questions about using the IP2Location Web 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:

4. IP location - Abbas Mandal (2017-09-07 00:51)
helpful class... - 0 replies
Read the whole comment and replies

3. marksumit - mark mark (2016-06-28 17:05)
very infromative... - 0 replies
Read the whole comment and replies

2. Error - Karl (2016-01-05 16:09)
traditional php script error output... - 3 replies
Read the whole comment and replies

1. Interesting - Sandro Alves Peres (2016-01-04 23:42)
Nice article... - 1 reply
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 (8)   Trackbacks (0)