Get city by IP with PHP

with the following snippet PHP you can get the city of a user just using their IP. The snippet is a PHP function that you can incorporate into your helpers and with which you will be able to know in an instant the city of any user who visits a website, without the need for it to be aware of it.

This code is especially useful when you do not use the browser’s geolocation with javascript or the user decides not to share their location with your site through the browser.

Content

  • Function obtained by the city through IP
  • How do you get the city with this PHP snippet?

Function obtained by the city through IP

Here is a simple PHP code.

A function that you get via an external api, which signals[email protected] of https://www.ipinfodb.com/ make available to us.

Look how easy:

function obtener_ciudad($ip) {
        
    $ip = '168.192.0.1'; // your ip address here
    $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
    if($query && $query['status'] == 'success')
    {
      	return $query['city'];
    }
        
}

How do you get the city with this PHP snippet?

The PHP script that I have shown you, as you will have seen, does not make use of any database nor does it perform any exceptional calculation.

You will ask yourself, how has the city of the IP been calculated? The process is simpler than it seems and is achieved thanks to the information that shows a specific page http://ip-api.com/php/.

In this script I issue a GET request with file_get_contents with one data per url $ip.

By doing this, the page server returns a result in serialized JSON.

With a bit of skill and the use of a PHP function we recover the HTML content related to City and the State. For this we use unserialize.

The different functions used to retrieve the city and state based on the IP are:

  1. php unserialize function, which allows us to pass a serialized text to a PHP array (in this case).
  2. The file_get_contents function which, in this case, receives a url from a website instead of a file, but in the end it collects the content of the url and returns it.

Leave a Reply