There is no function in php that can get user based timezone. But there is way around. First you have to grab user IP address, then you have make a call to a third party service to get geo information. Thus you can get user timezone.
The following function is fool-proof solution to get user IP using php so far. And credits goes to https://stackoverflow.com/a/38852532/7935051
<?php
function getClientIp() {
$ipAddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipAddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ipAddress = $_SERVER['REMOTE_ADDR'];
} elseif (getenv('REMOTE_ADDR')) {
$ipAddress = getenv('REMOTE_ADDR');
} else {
$ipAddress = 'Unknown';
}
return $ipAddress;
}
Now you have to depend on the third party services to get geo information. This is very true for this type of jobs. There are several free services on internet, for example, geoPlugin. You may use it. See more details.
// Gets the client IP
$userIp = getClientIp();
$geoInfo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip={$userIp}"));
// Gets the timezone
$timezone = $geoInfo['geoplugin_timezone'];
// Sets user timezone, otherwise uses default
if ($timezone) {
date_default_timezone_set($timezone);
} else {
date_default_timezone_set('Asia/Tokyo');
}
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
BTW you may debug $geoInfo
variables to get more information