Get user current location based on IP

Get user’s current location based on IP

Welcome back to shortlearner.com, in this post today we will see how to find user’s location with having their IP address. so most of the time we need to access the user’s location to analysis the location wise client base.
In the below PHP script first of all we will fetch the user’s IP address by using pre-defined PHP function and store the IP address in a $ip_address variable.


so simply we will pass this IP address to our third party platform that will return as a JSON array that having country, country code, state, city , zip, time zone, longitude and latitude as well.
here we are performing this task with the help of curl functionality.

Get user current location based on IP
<?php
$ip_address = $_SERVER['REMOTE_ADDR'];
$url = "http://ip-api.com/json/$ip_address";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
$arr_result = json_decode($response);
echo($response);
 ?>

so we got this JSON response.

 {"status":"success",
 "country":"United States",
 "countryCode":"US",
 "region":"MA",
 "regionName":"Massachusetts",
 "city":"Boston",
 "zip":"02110",
 "lat":42.358,
 "lon":-71.0526,
 "timezone":"America/New_York",
 "isp":"Leaseweb USA",
 "org":"Cooley, Manion, Moore \u0026 Jones, LLP","as":"AS30633 Leaseweb USA, Inc.",
 "query":"207.244.89.166"
}

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript