Как включить или выключить отображение ошибок в PHP.


Часто слышал о такой проблеме от других пользователей. Одним из-за хостера нужно скрыть появляющиеся ошибки, другим наоборот - понять, что происходит с их кодом, потому что ни одна ошибка не показывается. В этой статье постараюсь показать все основные способы отобразить / скрыть ошибки.

В скрипте PHP

1) В PHP есть всего лишь один оператор, который поддерживает систему управления ошибками - это знак @ . Он позволяет проигнорировать сообщение любое сообщение об ошибке. Его нужно ставить ПЕРЕД выражением, которое может её содержать.

В примере специально допущена ошибка, но она НЕ будет отображена

$value = @$var[$key];
2) Также можно перед проверяемым скриптом PHP можно вставить настройку параметра отображения ошибок (display_errors ). Он может приобретать значение либо On (показывать), либо Off (скрыть).

Ini_set("display_errors","On");
error_reporting("E_ALL");
И соответственно после кода, который проверялся на ошибки, выставить параметр обратно.

Ini_set("display_errors","Off");

Например, Вы хотите увидеть ошибки в скрипте

Ini_set("display_errors", "On"); // сообщения с ошибками будут показываться
error_reporting(E_ALL); // E_ALL - отображаем ВСЕ ошибки
$value = $var[$key]; // пример ошибки
ini_set("display_errors", "Off"); // теперь сообщений НЕ будет
Можно выставить наоборот (в верхнем off, а в нижнем on), чтобы в конкретном отрезке кода ошибки НЕ отображались.

В файле.htaccess

Чаще всего проблему решают именно указанием настроек в файле .htaccess , который располагается в корневой директории сайта. В строке php_flag display_errors нужно также выставить On или Off

Php_flag display_errors On
#показать все ошибки кроме предупреждений (Notice)
php_value error_reporting "E_ALL & ~E_NOTICE"

В файле php.ini

Как видите, параметр можно указать в нескольких местах. Однако, если у Вы хотите, чтобы целиком на сайте этот параметр имел определённое значение, то проще выставить его в файле php.ini.(к нему на хостинге не всегда может быть доступ), но в этом случае можно будет даже обойти настройки всего хостинга

В php.ini :

Error_reporting = E_ALL
display_errors On
В верхней строке выбираем все виды ошибок, в нижней даём добро на их отображение.

После правок необходимо перезапустить Apache, чтобы настройки были изменены и вступили в силу (graceful или restart):

Sudo apachectl -k graceful

В каком порядке обрабатывается параметр ошибок

В самом начале учитывается параметр php.ini , затем.htaccess , а после то, что указано непосредственно в скрипте PHP. Так что если что-то не сработало, то смотрим по цепочку выше, возможно, там настройка другая.

Как обычно спасибо за внимание и удачи! Надеюсь статья была полезна!

При отладке скриптов на PHP обычное дело заполучить в браузере «белый экран». Что в большинстве случаев говорит об остановке выполнения PHP кода из-за ошибки. PHP интерпретатор позволяет выводить служебную информацию об ошибках на экран, что существенно облегчает отладку. Но по-умолчанию (в большинстве случаев) такое поведение из соображений безопасности отключено, то есть сообщения об ошибках PHP на экран не выводятся.

В этой статье я расскажу как заставить PHP выводить сообщения об ошибках на экран монитора в окне браузера. Инструкция справедлива для случая когда вы используете веб сервер Apache и если PHP для Вашего сайта подключен как модуль Apache.

Вывод ошибок на экран следует включать только во время отладки сайта. Наличие такого кода может негативно сказаться на безопасности веб-приложения.

Включение вывода ошибок PHP на экран с помощью файла.htaccess

Это очень удобный способ для отладки PHP кода. Работает практически во всех случаях. В папку со скриптом на сайте помещаем файл.htaccess со следующим содержимым:

Php_flag display_errors on php_flag display_startup_errors on php_flag error_reporting E_ALL

  • display_errors - включает опцию для вывода ошибок на экран вместе с остальным кодом.
  • display_startup_errors - включает опцию вывода ошибок, возникающих при запуске PHP, когда еще не работает директива display_errors.
  • error_reporting - указывает, какие ошибки выводятся по уровню значимости. При значении директивы E_ALL отображаются все ошибки.

Включение вывода ошибок PHP на экран в коде файла PHP

Этот способ удобен тем, что выводом ошибок на экран вы управляете в самом скрипте PHP. Параметры, заданные с помощью функции ini_set(), имеют более высокий приоритет и перекрывают директивы php.ini и .htaccess . Разместите следующий код в начале PHP файла:

Ini_set("display_errors", 1); ini_set("display_startup_errors", 1); ini_set("error_reporting", E_ALL);

Включение вывода ошибок PHP на экран с помощью файла php.ini

Этот способ актуален когда вы являетесь администратором сервера. В файле php.ini отредактируйте следующие строки (добавьте при необходимости):

Display_errors = On display_startup_errors = On error_reporting = E_ALL

Лучший способ вывода PHP ошибок на экран

На мой взгляд обычному пользователю удобнее всего использовать .htaccess , особенно если у вас больше чем один PHP файл. Способ №2 удобен для отладки одного php файла, чтобы не затрагивать уровень вывода ошибок для других php скриптов. Вариант с php.ini подойдет только администраторам сервера, но зато его действие распространяется на все сайты расположенные на данном сервере.

Благодарности

При написании статьи были использованы следующие источники.

Включение отображения ошибок в PHP-скриптах может потребоваться для отладки сайта.

За протоколирование и уровень обработки ошибок в PHP отвечают директивы display_errors и error_reporting .

  • Директива display_errors определяет, требуется ли выводить ошибки на экран вместе с остальным выводом.
  • Директива error_reporting задает уровень протоколирования ошибок, т.е. какие именно ошибки и предупреждения PHP выводить.

Из соображений безопасности на серверах виртуального хостинга вывод ошибок PHP выключен.
В случае, если PHP для Вашего сайта подключен как модуль Apache (этот способ используется на хостинге по умолчанию) , то для вывода всех поддерживаемых ошибок и предупреждений достаточно добавить строки

Php_flag display_errors on
php_value error_reporting -1

в файл с именем .htaccess , размещающийся в папке public_html сайта.

Отредактировать файл можно, например, в разделе «Файловый менеджер » .
Если файла.htaccess нет, то его следует создать.

В разделе «Домены» в колонке "Папка" можно узнать, где именно размещается папка public_html сайта.

После включения вывода ошибок необходимо повторить заход на сайт, либо обновить страницу, нажав F5 в браузере. На странице должна отобразиться отладочная информация, доступная по сайту.

Следует иметь в виду, что если в скриптах сайта перед именами функций присутствует оператор подавления ошибок (символ "@"), то несмотря на прописанные в.htaccess директивы, вывод ошибок производиться не будет.

Дополнительная информация

  • В случае, если PHP для сайта подключен в режиме CGI, изменение параметров PHP производится в файле php.ini сайта. Для вывода всех ошибок и предупреждений необходимо внести в указанный файл строки

Display_errors = On
error_reporting = E_ALL

  • Вывод ошибок также может задаваться непосредственно в скриптах сайта с помощью функции ini_set() . Например, для включения вывода всех ошибок служат строки

Ini_set("display_errors", 1);
ini_set("error_reporting", E_ALL);

Параметры, заданные с помощью функции ini_set() , имеют более высокий приоритет и перекрывают директивы php.ini и.htaccess.

  • Вывод ошибок на экран следует включать только во время отладки сайта. Наличие такого кода может негативно сказаться на безопасности веб-приложения.
For further details and definitions of the PHP_INI_* modes, see the .

Here"s a short explanation of the configuration directives.

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants , and in php.ini . To set at runtime, use the error_reporting() function. See also the display_errors directive.

PHP 5.3 or later, the default value is E_ALL & ~ E_NOTICE & ~ E_STRICT & ~ E_DEPRECATED . This setting does not show E_NOTICE , E_STRICT and E_DEPRECATED level errors. You may want to show them during development. Prior to PHP 5.3.0, the default value is E_ALL & ~ E_NOTICE & ~ E_STRICT .

Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr is better to be written as $arr["item"] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Prior to PHP 5.4.0 E_STRICT was not included within E_ALL , so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

Note : PHP Constants outside of PHP

Using PHP Constants outside of PHP, like in httpd.conf , will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL ) will likely change. So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL ).

display_errors string

This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

Value "stderr" sends the errors to stderr instead of stdout . The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean .

This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Although display_errors may be set at runtime (with ini_set() ), it won"t have any effect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP"s startup sequence are not displayed. It"s strongly recommended to keep display_startup_errors off, except for debugging.

Log_errors boolean

Tells whether script error messages should be logged to the server"s error log or error_log . This option is thus server-specific.

You"re strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg , but not to explicitly called functions such as error_log() .

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ , may also be used. ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line unless is set true.

Ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

Report_memleaks boolean

If this parameter is set to On (the default), this parameter will show a report of memory leaks detected by the Zend memory manager. This report will be send to stderr on Posix platforms. On Windows, it will be send to the debugger using OutputDebugString(), and can be viewed with tools like » DbgView . This parameter only has effect in a debug build, and if error_reporting includes E_WARNING in the allowed list.

Track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg .

Html_errors boolean

If enabled, error messages will include HTML tags. The format for HTML errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext .

If disabled, error message will be solely plain text.

Xmlrpc_errors boolean

If enabled, turns off normal error reporting and formats errors as XML-RPC error message.

Xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

Docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by "/manual/" you can simply use docref_root=/manual/ . Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html . It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.сайт%2F"

Most of the time you want the docref_root value to end with a slash "/" . But see the second example above which does not have nor need it.

This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

The value of docref_ext must begin with a dot "." .

error_prepend_string string

String to output before an error message.

Error_append_string string

String to output after an error message.

Error_log string

Name of the file where script errors should be logged. The file should be writable by the web server"s user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows it means the event log. See also: syslog() . If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI. See also error_log() .

Syslog.facility string

Specifies what type of program is logging the message. Only effective if error_log is set to "syslog".

Syslog.filter string

Specifies the filter type to filter the logged messages. Allowed characters are passed unmodified; all others are written in their hexadecimal representation prefixed with \x . There are three supported filter types:

  • all – all characters
  • no-ctrl – all characters except control characters
  • ascii – all printable ASCII characters and NL
Only effective if