2

I want to set the timezone to the visitor's timezone.

I am doing it like this way:

$ip = $_REQUEST['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
  date_default_timezone_set($query['timezone']);
} else {
  echo 'Unable to get location';
}

However, when another visitor visits the site he will have the timezone of the previous visitor ...

Why doesn't date_default_timezone clears? Is there's any solution to that?

Any help would be appreciated.

Thanks!

Saveen
  • 4,120
  • 14
  • 38
  • 41
Mario
  • 1,374
  • 6
  • 22
  • 48

2 Answers2

3

$_REQUEST is used to get data from GET/POST request. It should be $_SERVER['REMOTE_ADDR']

Code

$ip = $_SERVER['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
if($query && $query['status'] == 'success') {
  date_default_timezone_set($query['timezone']);
  echo 'timezone set to '.$query['timezone'];
} else {
  echo 'Unable to get location';
}

Output

timezone set to Asia/Kolkata

Explanation:

$_REQUEST['REMOTE_ADDR'] have no value, mean $ip is empty. If you query http://ip-api.com/php/ without ip, it'll get request ip by default and shows that request data not ip data. That's why you're getting same timezone for every visitors.

Bonus

You can get visitors timezone without using any API. $_SERVER['COOKIE'] have timezone of visitors.

snippet

parse_str($_SERVER['HTTP_COOKIE'], $cookie);
if(isset($cookie['timezone'])){
   date_default_timezone_set($cookie['timezone']);
}
else{
   echo 'Unable to get location'; //or do something!
}
Shahnawaz Kadari
  • 1,423
  • 1
  • 12
  • 20
  • 1
    Thank you very much for the solution and the bonus too! I didn't know that the `HTTP_COOKIE` header would contain such value. – Mario Aug 12 '18 at 07:34
  • You're welcome! If you want more information like visitor's user-agent etc... you can `print_r($_SERVER);` `Happy Coding` – Shahnawaz Kadari Aug 12 '18 at 07:39
0

Unfortunately, the answer of "Smartpal" is very good but I still have the same problem with it.

So I've heard that date_default_timezone_set() is outdated and old - That's why I've switched to the DateTime() class.

and now instead of using date('G') I can do it like that:

$ip = $_SERVER['REMOTE_ADDR']; // the IP address to query
$query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
$tz = $query['timezone'];
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz));
$dt->setTimestamp($timestamp);
echo $dt->format('G');

This worked fine for me.

Source of the answer: https://stackoverflow.com/a/20289096/8524395

Mario
  • 1,374
  • 6
  • 22
  • 48