A more modern answer to this question is to put a javascript function on your landing page that sends the information to your PHP backend. I've put in some debugging and verbose options for beginners to use.
<script>
// Function to send the timezone to the server
function setTimezoneOnPageLoad() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; // Get the user's timezone
// Make the AJAX request
fetch('/set-timezone', {
method: 'POST', // Use POST for sending data
headers: {
'Content-Type': 'application/json', // Inform the server we're sending JSON
},
body: JSON.stringify({ timezone: timezone }), // Send the timezone as JSON
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json(); // Parse JSON response
})
.then(data => {
// Check the success flag in the JSON response
if (data.success) {
console.log(`Success: ${data.message}`);
} else {
console.error(`Error: ${data.error}`);
}
})
.catch(error => {
// Catch and log any errors
console.error('AJAX request failed:', error);
});
}
// Fire the function when the page is fully loaded
document.addEventListener('DOMContentLoaded', setTimezoneOnPageLoad);
</script>
Then on the php receiving this call (in this example /set-timezone is the route to your php code):
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json'); // Set the correct response type
$data = json_decode(file_get_contents('php://input'), true);
session_start();
$_SESSION['timezone']='';
if (!empty($data['timezone'])) {
$timezone = htmlspecialchars($data['timezone'], ENT_QUOTES, 'UTF-8');
// Validate and set the timezone
if (in_array($timezone, timezone_identifiers_list())) {
date_default_timezone_set($timezone);
// Send a structured response
echo json_encode([
'success' => true,
'message' => "Timezone set successfully.",
'timezone' => $timezone,
]);
$_SESSION['timezone']=$timezone
} else {
echo json_encode([
'success' => false,
'error' => "Invalid timezone.",
]);
}
} else {
echo json_encode([
'success' => false,
'error' => "Timezone not provided.",
]);
}
exit;
}
Now your backend can keep track of this user's session timezone in $_SESSION['timezone']. You can see where this is supported here https://caniuse.com/?search=Intl.DateTimeFormat().resolvedOptions().timeZone for about 96% of all global browsers.