In PHP, there is no direct way to get geolocation of an IP address. Therefore we have to use third party API to get geolocation from ip address.
There are many paid and free APIs available to get geolocation from ip address. I found a very simple and easy api freegeoip.net. It is a public RESTful web service API for searching geolocation of IP addresses and host names. freegeoip.net API usage is limited to 10,000 queries per hour and it is absolutely free. Most important we don’t need to register for api key to use this API.
Usage
freegeoip.net/{format}/{ip_or_hostname}
The API supports both HTTP and HTTPS. It provides the result in csv, xml and json formats.
Function IP2Geolocation
function ip2geolocation($ip) { # api url $apiurl = 'http://freegeoip.net/json/' . $ip; # api with curl $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiurl); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $data = curl_exec($ch); curl_close($ch); # return data return json_decode($data); }
Now just pass your IP address to this function to get geolocation as below:
$geolocation = ip2geolocation('8.8.8.8'); $geolocation->ip; $geolocation->country_name; $geolocation->city; $geolocation->latitude; $geolocation->longitude;
I hope this post will help you to get geolocation from IP address.