You can do it by two way. Send it from browser to server by Javascript OR use one of "Location-by-IP" services
Javascript solution you can find here get user timezone (thanks to @bennes)
But If you want to do it only on server side you can use this service https://timezoneapi.io/developers/ip-address
Here is example
// Get IP address
$ip_address = getenv('HTTP_CLIENT_IP') ?:
getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?:
getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?:
getenv('REMOTE_ADDR');
// Get JSON object
$jsondata = file_get_contents("http://ip-api.com/json/" . $ip_address);
// Decode
$data = json_decode($jsondata, true);
// Example: Get the city parameter
echo "City: " . $data['city'] . "<br>";
// Example: Get the users time
echo "Time: " . $data['timezone'] . "<br>";
Of course better to save offset to $_SESSION. Otherwise it'll generate outgoing request each time.
So you need someting like
session_start();
if (!isset($_SESSION['offset_hours'])) {
$ip_address = getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR');
$jsondata = file_get_contents("http://timezoneapi.io/api/ip/?" . $ip_address);
$data = json_decode($jsondata, true);
if($data['meta']['code'] == '200'){
$_SESSION['offset_hours']= $data['data']['datetime']['offset_hours'];
}
}
echo $_SESSION['offset_hours']; // Here is offset in hours