- Php default timezone warning
- Сообщение об ошибке date.timezone в PHP последних версий
- PHP RFC: Remove the date.timezone warning
- Proposal
- Proposed PHP Version(s)
- Unaffected PHP Functionality
- Feedback
- «Won’t this make life more difficult for end users?»
- «Users are idiots and can’t be trusted»
- «Can’t you just define the timezone in the command line? Like: `php -d date.timezone=UTC foo.php`»
- Proposed Voting Choices
- PHP date.timezone warning
- Ошибка «It is not safe to rely on the system’s timezone settings»
- Как исправить ошибку изменением параметра в конфигурации PHP
- Способ А
- Способ Б
- 9 комментариев
- Php default timezone warning
- Сообщение об ошибке date.timezone в PHP последних версий
Php default timezone warning
БлогNot. Сообщение об ошибке date.timezone в PHP последних версий
Сообщение об ошибке date.timezone в PHP последних версий
Маленький ответ на маленький вопрос. PHP последних версий довольно строг в отношении вывода сообщений об ошибках и предупреждений, скорее всего, в Вашем файле настроек стоит
error_reporting = E_ALL & ~E_DEPRECATED
Это, в частности, означает, что вывод предупреждений (Warnings, директива E_WARNING ) не подавлен, поэтому при ненастроенном «часовом поясе по умолчанию» каждый вызов функции date(. ) , в котором не подавлен вывод ошибок ( @date(. ) ), да и другие собщения об ошибках будут сопровождаться предупреждением вида
Warning: Unknown: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'UTC' for '6.0/no DST' instead in [ИМЯ_ФАЙЛА] on line [НОМЕР_СТРОКИ]
Просто поставьте в активном файле php.ini настройку date.timezone в секции [DATE] , например:
[Date] date.timezone = "Europe/Moscow"
для часового пояса GMT+6 — если лень искать в списках свой город. — не надо так делать, всё-таки значение зоны из спецификации; а вот без кавычек можно:
[Date] date.timezone = Europe/Moscow
Узнать, откуда подключён файл настроек php.ini, можно, выполнив это:
Ответ содержится в первой таблице в строке Loaded Configuration File
Начиная с PHP 5.1.0 можно установить временную зону по умолчанию для всех функций скрипта и без правки файла php.ini — для этого достаточно вызвать метод date_default_timezone_set с параметром-идентификатором временной зоны (см. ссылку выше).
Например, для Новосибирска делаем так:
date_default_timezone_set ('Asia/Novosibirsk');
Ещё лучше предусмотреть в скрипте соответствующую настройку.
Ещё я делаю так где-нибудь в начале скрипта (лучше всего в коде, выполняющемся 1 раз):
@date_default_timezone_set (date_default_timezone_get()); //Чтоб дальше не ругался предупреждениями на date()
14.02.2011, 19:01 [17257 просмотров]
PHP RFC: Remove the date.timezone warning
PHP should be usable without configuring it through either an ini file or defining settings on the command line. Currently this is not possible as the date.timezone is required to be set, despite it defaulting to the best option.
“date.timezone” is the only setting that is required to be set. Every other setting, including those that have security implications default to sensible values silently; defaulting to sensible values does not appear to cause any problem for users.
The error message becomes entirely tedious when working with anything other than a single installed version of PHP.
For example when you want to run the unit tests for a library against all the different versions of PHP that library supports, you should be able to do so by downloading each of the PHP versions you want to test against, and invoking the PHP executables from the download location, rather than having to install it first.
Proposal
The current behaviour when the data.timezone ini entry is not set is to:
The proposal is just to remove the warning message. The behaviour of setting the timezone to be UTC would not be changed. This will allow people to run PHP without an ini file without having error messages.
Proposed PHP Version(s)
Targeting the next minor version. (In this case PHP 7, being a major too.)
Unaffected PHP Functionality
If the date.timezone ini setting is set but invalid, a warning is still thrown.
Feedback
«Won’t this make life more difficult for end users?»
No. For users who install PHP through a distribution, the ini file is created by the package maintainer. They should set it to the systems timezone. (Some don’t, but that is the fault of the distributions.)
For end users who compile from source they can either modify the ini file that is used by PHP in the compile step or they could add it themselves when PHP is built e.g. For Debian they could easily stick the following in a post-install hook to fix it:
echo 'date.timezone='`cat /etc/timezone` > /etc/php/config.d/date.ini
People who are compiling PHP from source are perfectly capable of setting all ini settings that need to be set.
The only people who this RFC will affect are:
Those who use multiple versions of PHP or otherwise use PHP without going through the install process. This RFC will be beneficial to these users.
People who have accidentally deleted their ini files from their production system. These users have bigger issues than this RFC can address.
Still, it is weird, to have that one setting emit a warning, but other much more important settings don’t. The ini settings have defaults and they should be used.
«Users are idiots and can’t be trusted»
Well, yes. But there are many things that must be set in an ini file for PHP to be usable in a production environment. The person installing PHP needs to be capable of setting all of these. The timezone setting is not the most important setting that needs to be set so it’s not good that PHP gives a warning message when it is not set.
«Can’t you just define the timezone in the command line? Like: `php -d date.timezone=UTC foo.php`»
This is a painful hack. For people who spend a significant amount of time either developing PHP, PHP extensions or testing userland code against multiple PHP versions, they should be able to run PHP code without getting slapped for the temerity of not using an ini file and without being forced to set an ini setting to the same default value it is going to use anyway.
Proposed Voting Choices
Remove this warning (50%+1 vote) — Vote began 2015-02-16 and ended 2015-02-24.
PHP date.timezone warning
Message: date() [function.date]: It is not safe to rely on the system’s timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/New_York’ for ‘EST/-5.0/no DST’ instead
I have edited my php.ini and added this to the end of it: date.timezone = «America/New_York» After saving the php.ini and restarting Apache, I still get the error. I have also tried rebooting the entire server to no avail. I’m running cPanel/WHM on CentOS 5.6 if that makes any difference. Also, the PHP handler is suphp. I’m not sure what to try next. any guidance?
Its not an error its a message so everything will work fine but php is informing you that its not good idea to rely on system timezone setting .. thats all . but its strange that after you changed setting the message is still there :/
Presuming you have the right php.ini file, 3 observations (although all may be irrelevant): a) There should already be an entry for date.timezone in your php.ini file (i.e. your new entry might not take precedence) b) There is a specific [Date] section in php.ini — which is not at the bottom of the file, entries outside of that might not be processed as expected; c) The timezone doesn’t need to be quoted — again, I am uncertain of the effect. Try php -i | grep timezone and see what you get.
Ошибка «It is not safe to rely on the system’s timezone settings»
Как исправить ошибку изменением параметра в конфигурации PHP
Чтобы устранить ошибку «It is not safe to rely on the system’s timezone settings. », установите в файле php.ini подходящую временную зону для параметра date.timezone в конфигурации PHP. Пример значения временной зоны: europe/moscow.
Если у вас нет доступа к файлу php.ini, укажите временную зону в файлах Вебасиста любым из этих способов.
Способ А
В файле .htaccess в корневой директории Вебасиста добавьте на новой строке команду
php_value date.timezone 'Europe/Moscow'
Способ Б
В файле wa-config/SystemConfig.class.php после тега
на следующей новой строке добавьте команду
date_default_timezone_set('Europe/Moscow');
Более подробно о параметре date.timezone написано в документации PHP.
9 комментариев
Проделал все процедуры. Ничего не помогает. Также выдаёт при входе в админку или настройки: Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone ‘UTC’ for now, but please set date.timezone to select your timezone. in /home3/kanyukov/public_html/webasyst/kernel/functions.php on line 7717 Warning: date(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone ‘UTC’ for now, but please set date.timezone to select your timezone. in /home3/kanyukov/public_html/webasyst/kernel/includes/pear/Date/TimeZone.php on line 874
И это не при установке. Работал нормально.2 года. А вот с неделю такая беда.
Помогите. Кто сталкивался с такой ситуацией.
Доброе время суток! Обнаружили что у нас достаточно давно не отрабатываются триггерные рассылки. от CRON приходи вот такая ошибка:
Warning: strtotime(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /home/qshop1/q-shop.in.ua/www/wa-apps/shop/lib/cli/shopFollowup.cli.php on line 29
Так же выяснили что данная проблема началась сразу после обновления на SHOP-SCRIPT 7.2 , правда обнаружили проблему значительно позже. В файле на который ссылается ошибка следующий код
foreach ($fm->getAllEnabled() as $f) < $search_params = array( 'from' =>date('Y-m-d H:i:s', strtotime($f['last_cron_time']) - 24 * 3600), 'to' => date('Y-m-d H:i:s', time() - $f['delay'] - 1 * 3600), 'state_id' => $f['state_id'], );
Php default timezone warning
БлогNot. Сообщение об ошибке date.timezone в PHP последних версий
Сообщение об ошибке date.timezone в PHP последних версий
Маленький ответ на маленький вопрос. PHP последних версий довольно строг в отношении вывода сообщений об ошибках и предупреждений, скорее всего, в Вашем файле настроек стоит
error_reporting = E_ALL & ~E_DEPRECATED
Это, в частности, означает, что вывод предупреждений (Warnings, директива E_WARNING ) не подавлен, поэтому при ненастроенном «часовом поясе по умолчанию» каждый вызов функции date(. ) , в котором не подавлен вывод ошибок ( @date(. ) ), да и другие собщения об ошибках будут сопровождаться предупреждением вида
Warning: Unknown: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'UTC' for '6.0/no DST' instead in [ИМЯ_ФАЙЛА] on line [НОМЕР_СТРОКИ]
Просто поставьте в активном файле php.ini настройку date.timezone в секции [DATE] , например:
[Date] date.timezone = "Europe/Moscow"
для часового пояса GMT+6 — если лень искать в списках свой город. — не надо так делать, всё-таки значение зоны из спецификации; а вот без кавычек можно:
[Date] date.timezone = Europe/Moscow
Узнать, откуда подключён файл настроек php.ini, можно, выполнив это:
Ответ содержится в первой таблице в строке Loaded Configuration File
Начиная с PHP 5.1.0 можно установить временную зону по умолчанию для всех функций скрипта и без правки файла php.ini — для этого достаточно вызвать метод date_default_timezone_set с параметром-идентификатором временной зоны (см. ссылку выше).
Например, для Новосибирска делаем так:
date_default_timezone_set ('Asia/Novosibirsk');
Ещё лучше предусмотреть в скрипте соответствующую настройку.
Ещё я делаю так где-нибудь в начале скрипта (лучше всего в коде, выполняющемся 1 раз):
@date_default_timezone_set (date_default_timezone_get()); //Чтоб дальше не ругался предупреждениями на date()
14.02.2011, 19:01 [17257 просмотров]