Get the longitude and latitude as user's machine in PHP

The only way to geolocate on the serverside would be to use a lookup table for the IP adress. There are services that provide this for you, so you could do this :

$ip  = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$url = "http://freegeoip.net/json/$ip";
$ch  = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);

if ($data) {
    $location = json_decode($data);

    $lat = $location->latitude;
    $lon = $location->longitude;

    $sun_info = date_sun_info(time(), $lat, $lon);
    print_r($sun_info);
}

It won't always be very accurate though. In javascript you would have access to the HTML5 Geolocation API, or Google Maps, but reverse geocoding with Google requires you to use a map, as per the TOS.

NOTE (2019): The service used in the example, FreeGeoIP has shut down, I'll leave the answer for posterity, as there are surely other services offering the same service.

Tags:

Php