Ideally, you should configure each server's php.ini where date.timezone can be set:
; ...
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = 'America/Chicago'
; ...
A list of acceptable timezones can be found in the PHP manual.
If you'd rather set it on each script here's a platform independent function that sets it:
<?php
function setTimezone($OSXPassword = null){
$timezone = null;
switch(true){
//Linux (Tested on Ubuntu 14.04)
case(file_exists('/etc/timezone')):
$timezone = file_get_contents('/etc/timezone');
$timezone = trim($timezone); //Remove an extra newline char.
break;
//Windows (Untested) (Thanks @Mugoma J. Okomba!)
case(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'):
$timezone = exec('tzutil /g');
break;
//OSX (Tested on OSX 10.11 - El Capitan)
case(file_exists('/usr/sbin/systemsetup')):
if(!isset($OSXPassword)){
$OSXPassword = readline('**WARNING your input will appear on screen!** Password for sudo: ');
}
$timezone = exec("echo '" . $OSXPassword ."' | sudo -S systemsetup -gettimezone");
$timezone = substr($timezone, 11);
break;
}
if(empty($timezone)){
trigger_error('setTimezone could not determine your timezone', E_USER_ERROR);
} else {
date_default_timezone_set($timezone);
}
return $timezone;
}
setTimezone();
?>
As you can tell, support for OSX is sketchy.
The only decent way of getting a timezone on OSX is through systemsetup which requires super user to run. I really hate the practice of storing root's password in a PHP script but I've included the option for completeness - use with caution, this is a security vulnerability. On OSX, if root's password is not provided the script will attempt to get it from user input.
date_default_timezone_set()date_default_timezone_set()