How can I determine user's current location based on IP (I guess it works this way).
The HTML Geolocation API is used to locate a user's position.
To obtain the user's current location, you can call the getCurrentPosition() method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed.
The Geolocation method watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes.
<?php $user_ip = getenv('REMOTE_ADDR'); $geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $country = $geo["geoplugin_countryName"]; $city = $geo["geoplugin_city"]; ?>
Edited
Change freegeoip.net into ipinfo.io
<?php function get_client_ip() { $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'; } return $ipaddress; } $PublicIP = get_client_ip(); $json = file_get_contents("http://ipinfo.io/$PublicIP/geo"); $json = json_decode($json, true); $country = $json['country']; $region = $json['region']; $city = $json['city']; ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With