To get Geo location (country, city, isp, etc.) based on website visitor IP in PHP application can use API from ip-api.com. In this article, I will share how to get geolocation information from site visitors using PHP.
IP-API is a free GEO LOCATION IP service with multiple response formats. In addition to free, its use is also quite easy to apply. However, free facilities have some limitations. IP-API server will automatically be banned IP Addresses if making more than 150 requests per minute. If you need more data from IP-API, you can buy a pro service.
Another article: Angular 4 Tutorial For Beginner With Simple App Project
Tutorial get GEOLOCATION IP Information with PHP
Make a function to get Ip visitors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | function get_header_info(){ $header = array(); $ipaddress = ''; if (isset($_SERVER['HTTP_CLIENT_IP'])) $ipaddress = $_SERVER['HTTP_CLIENT_IP']; else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; else if(isset($_SERVER['HTTP_X_FORWARDED'])) $ipaddress = $_SERVER['HTTP_X_FORWARDED']; else if(isset($_SERVER['HTTP_FORWARDED_FOR'])) $ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; else if(isset($_SERVER['HTTP_FORWARDED'])) $ipaddress = $_SERVER['HTTP_FORWARDED']; else if(isset($_SERVER['REMOTE_ADDR'])) $ipaddress = $_SERVER['REMOTE_ADDR']; else $ipaddress = 'UNKNOWN'; $header['ipaddress'] = $ipaddress; if(isset($_SERVER['HTTP_REFERER'])) { $header['referer']= $_SERVER['HTTP_REFERER']; }else { $header['referer'] =''; } $header['useragent'] = $_SERVER['HTTP_USER_AGENT']; $header['requesturi'] = $_SERVER['REQUEST_URI']; return $header; } |
Create a function to call the geolocation API from ip-api.com
1 2 3 4 5 6 7 8 9 10 | function geolocation($ip){ $ch = curl_init('http://ip-api.com/json/'.$ip); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $xresult = curl_exec($ch); $xresult = json_decode($xresult,true); return $xresult; } |
Test both functions above using the following code
1 2 3 4 5 6 7 8 9 10 11 | $header = get_header_info(); echo '<h3>Array from get_header_info function:</h3><br/>'; foreach ($header as $key => $value) { echo $key.' => '.$value.'<br/>'; } echo '<br/>'; $getloc = geolocation($header['ipaddress']); echo '<h3>Array from geolocation function:</h3><br/>'; foreach ($getloc as $key => $value) { echo $key.' => '.$value.'<br/>'; } |
If successful you will get results like the following picture
Note: The above script does not work on the localhost server.
Conclusion:
To obtain information geolocation is very easy using API from ip-api.com. You can subscribe for €45 (3 months) for unlimited use of API
So my short tutorial on Simple Tutorial Get Geolocation IP With PHP, hopefully, useful
Leave a Reply