0

In the navbar.php file that's included on every page on my website, I want to set the timezone for every user. I've found a good js script that works perfectly for me. I can echo the variable and it correctly identifies 'Europe/Brussels' as my timezone. Now I want to be able to set this timezone variable as the timezone in PHP. This is a snippet of the code I currently have in my navbar.php file but it's not working..

<script type="text/javascript" src="domain/js/jstz.js"></script>

<script>
  $.ajax({
     var tz = jstz.determine(); 
     var tzname = tz.name();
     'url': 'navbar.php',
     'type': 'POST',
     'data': 'timezone=' + tzname
  });       
</script>

<?php 

$usertimezone = $_POST['timezone'];
date_default_timezone_set($usertimezone);

?>

Anyone who can see what's wrong with it and help me? Thanks!

  • 2
    you realize that PHP runs on the server, and JS runs on the client? That php code is gone/destroyed long BEFORE the js code ever has a chance to run, so you're accessing an undefined $_POST parameter, and setting your timezone to be `null`. – Marc B Mar 08 '16 at 15:21
  • Maybe this answer will help you http://stackoverflow.com/questions/4746249/get-user-timezone :) – Rômulo M. Farias Mar 08 '16 at 15:25
  • Thanks for your comment @MarcB . I'm fairly new to all this so I'm still learning. Do you know another way I could do this? I just need to set the timezone in PHP using the JS variable.. – Senne Vandenputte Mar 08 '16 at 15:25
  • setting the timezone like this is pointless. every request to php is independent of each other. you'd set the TZ in one instance of php, and then that setting is gone forever. you'd need to store the TZ in the session, and set it every time a request comes in to the server. – Marc B Mar 08 '16 at 18:30

1 Answers1

0

The problem is that the timezone is setup after the page has been loaded. The main page script always uses the default php timezone setting.
You should store the timezone value into a session variable:

navbar.php:

<?php 
session_start();
$usertimezone = $_POST['timezone'];
$_SESSION['timezone'] = $usertimezone;
?>

main.php (the script which loads the entire initial page)

<?php
session_start();
if (isset($_SESSION['timezone'])) {
  date_default_timezone_set($_SESSION['timezone']);  
}
?>
Dmitri Pavlutin
  • 18,122
  • 8
  • 37
  • 41
  • I did this, but still the same. When I echo my date_default_timezone_get() it still says America/New York, while the timezone variable should pass Europe/Brussels – Senne Vandenputte Mar 08 '16 at 15:36
  • On first main page load the timezone is not updated, because the session var is not setup yet. But on next loads it should be fine. Make sure that session is initialised before any output is sent. – Dmitri Pavlutin Mar 08 '16 at 15:38