If you have a web portal and you need to get the geolocation from an IP address of every user who has logged into your website, then you can do it very easily using simple PHP script.
Getting Geolocation will help you to identify user location. You can monitor the website traffic and behavior using this feature. This article dictates a PHP script for doing the same.
Get GeoLocation From an IP Address Of User
To get geolocation we are using ipinfo API service. Pass the user IP address as parameter and it will return the IP location details like IP address, Host name, City, Location etc..
Here is the full code to first get the IP address of logging user, then to get the location details for the IP address and finally to save the details into database (if required).
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<?php /* * * code to get the IP address of the user * */ if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } /* * code to get user location details using his IP address * * */ $user_ip = $ip; $url = "http://ipinfo.io/".$user_ip; $ip_info = json_decode(file_get_contents($url)); $ip = $ip_info->ip; $host = $ip_info->hostname; $city = $ip_info->city; $region = $ip_info->region; $country = $ip_info->country; $loc = $ip_info->loc; $loc_array = explode(',',$loc); $lat = $loc_array[0]; $long = $loc_array[1]; $org = $ip_info->org; $postal = $ip_info->postal; echo '<strong>IP Address </strong>'.$ip.'<br>'; echo '<strong>Host Name </strong>'.$host.'<br>'; echo '<strong>City </strong>'.$city.'<br>'; echo '<strong>Region </strong>'.$region.'<br>'; echo '<strong>Country Code </strong>'.$country.'<br>'; echo '<strong>Location </strong>'.'Lat'.$lat.''.'Long'.$long.'<br>'; echo '<strong>Org </strong>'.$org.'<br>'; echo '<strong>Portal Code </strong>'.$postal.'<br>'; /* * *Code to save user IP location details into database * * */ $con=mysql_connect("localhost","database username","database password"); if(!$con) { die('could not connect:'.mysql_error()); } mysql_select_db("database name",$con); $sql="INSERT INTO table_name (ip,host,city,region,country,lat,long,org,postal) VALUES ('$ip','$host','$city','$region','$country','$lat','$long','$org','$postal')"; if(!mysql_query($sql,$con)) { die('Error: ' . mysql_error($con)); } ?> |
This simple PHP script can be easily integrated and modified as per your need. Use this script on your website to get exact Geolocation from an IP address of user.