How to track user location in php

In this article, you will learn how to track the visitor's current location using the PHP programming language.

Geolocation in itself is an innovation that has saved, served and recommended incredible things, places to individuals all throughout the planet. By using geolocation, we can easily know how to go from one place to another. It can easily provide us with information, entertainment, security or weather updates.

For implementing this, we are using the HTML5 Geolocation API. The HTML5 Geolocation API is used to get the visitor's latitude and longitude and helps us to easily trace the visitor's full address (location, city, district, state, pincode), but this is possible only when the user clicks on the allow button of notification to share their current location. This notification is basically for privacy reasons.

How to track user location in php

Here is the simple code written in HTML5, PHP, and JavaScript to get the current visitor's location. The HTML5 Geolocation API is responsible for working in a secure context and providing visitors with their latitude and longitude. After that, we will call the Ajax file 'get_location.php' and pass the latitude and longitude to get the visitor's address.

So, let's first create a file name 'index.php' and call the jQuery library file in the head section as we have mentioned here. In the body section, we have created two JavaScript functions- getlocation() and visitorLocation(). The getlocation() function is called when you click the 'Get Current Location' button and the visitorLocation() function is called within it to get the latitude and longitude.

var lat = position.coords.latitude;
var long = position.coords.longitude;

After the above code, we have called the ajax file 'get_location.php' and passed the 'lat' and 'long' variables as parameters to the url.

1. index.php

<!DOCTYPE>
<html>
    <head>
        <title>Get Visitor's Current Location using PHP and JQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <style type="text/css">
            #container{ color:  #116997; border: 2px solid #0b557b; border-radius: 5px;}
            p{ font-size: 15px; font-weight: bold;}
        </style>
    </head>
    <body>
        <script type="text/javascript">
            function getlocation() {
                if (navigator.geolocation) { 
                    if(document.getElementById('location').innerHTML == '') {
                        navigator.geolocation.getCurrentPosition(visitorLocation);
                    } 
                } else { 
                    $('#location').html('This browser does not support Geolocation Service.');
                }
            }
            function visitorLocation(position) {
                var lat = position.coords.latitude;
                var long = position.coords.longitude;
                $.ajax({
                    type:'POST',
                    url:'get_location.php',
                    data:'latitude='+lat+'&longitude='+long,
                    success:function(address){
                        if(address){
                           $("#location").html(address);
                        }else{
                            $("#location").html('Not Available');
                        }
                    }
                });
            }
        </script>
        <input type="button" onclick="return getlocation()" value="Get Current Location" />
        <div id="container"><p>Your Current Location: <span id="location"></span></p></div>
    </body>
</html>
    

Then create another php file name 'get_location.php' and copy and paste the given code.

2. get_location.php


<?php
    if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
        //Send request and receive latitude and longitude
        $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
        $json = @file_get_contents($url);
        $data = json_decode($json);
        $status = $data->status;
        if($status=="OK"){
            $location = $data->results[0]->formatted_address;
        }else{
            $location =  'No location found.';
        }
        echo $location; 
    } 
?>

In the above code, first we request the Geocoding API in the following format, which returns the output in JSON format.

https://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';

Then, we have used the file_get_contents() to read the contents of the JSON file as a string and decode this using json_decode() function.

$json = @file_get_contents($url);
$data = json_decode($json);

And finally, we have received the current visitor's location address in the following variable.

$location = $data->results[0]->formatted_address;

How to get location of user in PHP?

The getCurrentPosition() method is used to get the visitor's position and showLocation() method is used to getting the visitor's address from the getLocation. php file using Ajax. HTML Code: After getting the visitor position, the address will be shown on the web page ( #location span).

How to get location from IP address in PHP?

From PHP.net: The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP. This is just a php module for the MaxMind database, which is payware.