php display all errors
Php display all errors
Краткое разъяснение конфигурационных директив.
Значение по умолчанию равно E_ALL &
E_NOTICE &
E_STRICT &
Замечание: PHP-константы за пределами PHP
Эта настройка определяет, требуется ли выводить ошибки на экран вместе с остальным выводом, либо ошибки должны быть скрыты от пользователя.
Эта функциональность предназначена только для разработки и не должен использоваться в готовых производственных системах (например, системах, имеющих доступ в интернет).
Несмотря на то, что display_errors может быть установлена во время выполнения (функцией ini_set() ), это ни на что не повлияет, если в скрипте есть фатальные ошибки. Это обусловлено тем, что ожидаемые действия программы во время выполнения не получат управления (не будут выполняться).
Даже если display_errors включена, ошибки, возникающие во время запуска PHP, не будут отображаться. Настойчиво рекомендуем включать директиву display_startup_errors только для отладки.
Отвечает за выбор журнала, в котором будут сохраняться сообщения об ошибках. Это может быть журнал сервера или error_log. Применимость этой настройки зависит от конкретного сервера.
Настоятельно рекомендуем при работе на готовых работающих web сайтах протоколировать ошибки там, где они отображаются.
Не заносить в журнал повторяющиеся ошибки. Ошибка считается повторяющейся, если происходит в том же файле и в той же строке, и если настройка ignore_repeated_source выключена.
Игнорировать источник ошибок при пропуске повторяющихся сообщений. Когда эта настройка включена, повторяющиеся сообщения об ошибках не будут заноситься в журнал вне зависимости от того, в каких файлах и строках они происходят.
Если настройка включена (по умолчанию), будет формироваться отчёт об утечках памяти, зафиксированных менеджером памяти Zend. На POSIX платформах этот отчёт будет направляться в поток stderr. На Windows платформах он будет посылаться в отладчик функцией OutputDebugString(), просмотреть отчёт в этом случае можно с помощью утилит, вроде » DbgView. Эта настройка имеет смысл в сборках, предназначенных для отладки. При этом E_WARNING должна быть включена в список error_reporting.
Если разрешена, сообщения об ошибках будут включать теги HTML. Формат для HTML-ошибок производит нажимаемые ссылки, ведущие на описание ошибки, либо функии, в которой она произошла. За такие ссылки ответственны docref_root и docref_ext.
Если запрещена, то ошибки будут выдаваться простым текстом, без форматирования.
Если включена, то нормальное оповещение об ошибках отключается и, вместо него, ошибки выводятся в формате XML-RPC.
Используется в качестве значения XML-RPC элемента faultCode.
Эта функциональность предназначена только для разработки, так как он облегчает поиск описаний функций и ошибок. Не используйте его в готовых производственных системах (например, имеющих доступ в интернет).
Строка, которая будет выводиться непосредственно перед сообщением об ошибке.
Строка, которая будет выводиться после сообщения об ошибке.
Указывает, какой тип программы регистрирует сообщение. Действует только в том случае, если опция error_log установлена в «syslog».
Тип фильтра raw доступен начиная с PHP 7.3.8 и PHP 7.4.0.
Определяет строку идентификатора, которая добавляется к каждому сообщению. Действует только в том случае, если опция error_log установлена в «syslog».
Как настроить отображение ошибок в PHP
В этом руководстве мы расскажем о различных способах того, как в PHP включить вывод ошибок. Мы также обсудим, как записывать ошибки в журнал (лог).
Как быстро показать все ошибки PHP
Что именно делают эти строки?
Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.
К сожалению, эти две директивы не смогут отображать синтаксические ошибки, такие как пропущенные точки с запятой или отсутствующие фигурные скобки.
Отображение ошибок PHP через настройки в php.ini
Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:
Директиву displayerrors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию iniset в коде PHP.
Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как «загруженный файл конфигурации» («loaded configuration file»).
.htaccess также имеет директивы для displaystartuperrors и display_errors.
Включить подробные предупреждения и уведомления
Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:
Для отображения предупреждений и уведомлений укажите «EWARNING | ENOTICE».
Также можно указать EERROR, EWARNING, EPARSE и ENOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «EALL &
ENOTICE», где EALL обозначает все возможные параметры функции errorreporting.
Более подробно о функции error_reporting ()
PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.
Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда ENOTICE передается в функцию errorreporting, эти необъявленные переменные будут отображаться.
Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «
» означает «нет», поэтому параметр
E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.
Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Errorreporting(EALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.
Включить ошибки php в файл с помощью функции error_log ()
У сайта на хостинге сообщения об ошибках не должны показываться конечным пользователям, но эта информация все равно должна быть записана в журнал (лог).
Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена к любому файлу журнала, определенному на веб-сервере.
Параметр 1 отправит журнал ошибок на почтовый ящик, указанный в третьем параметре. Чтобы эта функция работала, PHP ini должен иметь правильную конфигурацию SMTP, чтобы иметь возможность отправлять электронные письма. Эти SMTP-директивы ini включают хост, тип шифрования, имя пользователя, пароль и порт. Этот вид отчетов рекомендуется использовать для самых критичных ошибок.
Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.
Журнал ошибок PHP через конфигурацию веб-сервера
Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.
В nginx директива называется error_log.
Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.
Display All PHP Errors: Basic & Advanced Usage
A PHP application might produce many different levels of earning and errors during its execution. Being able to see these errors is essential for developers trying to troubleshoot a misbehaving application. However, developers often have trouble when trying to display errors from their PHP applications. Instead, their apps just fail silently.
If you are having problems with your PHP web application and need to display all the errors and warnings, you are in the right place. In this tutorial, we will explain all the different ways to enable PHP errors and warnings. We will also discuss how to write the errors to a log file and even collect them via the Retrace’s error tracking feature.
Quickly Show All PHP Errors
The quickest way to display all php errors and warnings is to add these lines to your PHP code file:
What Do These Lines of Code Do Exactly?
The ini_set function will try to override the configuration found in your PHP ini file.
The display_errors and display_startup_errors are just two of the directives that are available. The display_errors directive will determine if the errors will be displayed or hidden to the user. Usually, the dispay_errors directive should be turned off after development.
The display_startup_errors, however, is a separate directive because the display_errors doesn’t handle the errors that will be encountered during PHP’s startup sequence. The list of the directives that can be overridden by the ini_set function is found in the official documentation.
Unfortunately, these two directives won’t be able to display parse errors such as missing semicolons or missing curly braces. In this case, the PHP ini configuration must be modified.
Configure PHP.ini to Display All Errors
If adding some of the PHP code errors doesn’t show in the browser during testing, then the PHP ini configuration has some additional directives to handle this.
The display_errors directive must be set to “on” in the PHP ini file. This will display all the errors including syntax or parse errors that cannot be displayed by just calling the ini_set function in the PHP code. The PHP ini file can be found in the displayed output of phpinfo() function and is labeled loaded configuration file. This directive in the ini configuration must be set to off, if the web application is in production.
Enable Detailed Warnings and Notices
Sometimes, the warnings that seem not to affect the application at the start will cause some fatal errors in certain conditions. These warnings must be fixed because this means that the application won’t run normally under certain scenarios. In case these warnings cause a lot of errors, then it would be more practical to hide the errors and just show what the warning messages are.
For a developer, showing warnings and hiding errors is just as simple as adding a single line of code. To show warnings and notices, the parameter for the error reporting function will be “E_WARNING | E_NOTICE”. The error_reporting function can accept E_ERROR, E_WARNING, E_PARSE, and E_NOTICE parameters as bitwise operators. To report all errors except for notices, then the parameter is “E_ALL &
E_NOTICE” where E_ALL stands for all the possible parameters of the error_reporting function.
In-depth With the error_reporting() function
The error reporting function is a built-in PHP function that allows developers to control which and how many errors will be shown in the application. Remember, the PHP ini configuration has an error_reporting directive that will be set by this function during runtime.
PHP allows variables to be used even when not declared. This is not a standard practice because undeclared variables will cause issues for the application once it is used in loops and conditions. Sometimes, this also happens because the declared variable has a different spelling than the variable being used for conditions or loops. When E_NOTICE is passed in the error_reporting function, then these undeclared variables will be displayed in the web application.
The error reporting function allows you to filter which errors can be shown. The “
” character means “not” or “no” so the parameter
E_NOTICE means not to show notices. Notice the “&” and “|” characters in between the possible parameters. The “&” character is for “true for all”, while the “|” character represents either one as long as it is true. These two characters have the same meaning in PHP conditions OR and AND.
These three lines of codes do exactly the same thing, it will show all PHP errors. The error_reporting(E_ALL) is the most widely used among developers to show error messages because it is more readable and understandable.
Log PHP errors to a file using the error_log() function
During production, error messages must not be shown to the end users, but this information must still be recorded for tracing purposes. The best way to record these error messages on a production web application is to store it in log files.
One easy way to use log files is to use the error_log function, which accepts four parameters. The only required parameter is the first parameter, which contains the details about the error or what’s to be logged. The type, destination, and header are all optional parameters for this function.
The type parameter, if not defined, will be 0 by default, which means this log information will be appended to whatever log file is defined in the web server.
The type 1 parameter will email an error log specified in the third parameter. To make this feature work, the PHP ini must have a proper SMTP configuration to be able to send out emails. These SMTP ini directives include host, encryption type, username, password, and port. This kind of error reporting is advisable to logging or notifying errors that need to be fixed as soon as found.
To log messages in a separate file defined by the configuration of the web server, then type 3 must be used. The third parameter will serve as the location of the log file and must be writable by the web server. The location of the log file can be a relative path to where this code is called or an absolute path.
Log PHP Errors Through the Web Server Configuration
For Apache, these files must be added to the virtual host of the specific website or application, usually located inside the sites-available folder for Ubuntu or httpd-vhosts file in Windows.
For nginx, similar to Apache, the directive is just called error_log. For both Apache and nginx web servers, the log files must be writable by the web server. Luckily, upon installation, the folders for the log files of these two web servers are already writable.
Automatically Collect PHP Errors With Retrace APM
One of the great features of Retrace is its ability to automatically collect all unhandled errors in your PHP application. Our PHP extension will catch the exception and forward them automatically to Retrace.
With Retrace, all the errors are automatically logged and formatted so that it can be viewed easily. Retrace will not only show what errors have occurred but also analyzes where and what caused it. The time and number of occurrences are also shown in the logs so that it would be a lot easier to focus on which issue to prioritize.
error_reporting
(PHP 4, PHP 5, PHP 7, PHP 8)
error_reporting — Задаёт, какие ошибки PHP попадут в отчёт
Описание
Функция error_reporting() задаёт значение директивы error_reporting во время выполнения. В PHP есть много уровней ошибок. Используя эту функцию, можно задать уровень ошибок времени выполнения скрипта, которые попадут в отчёт. Если необязательный аргумент error_level не задан, error_reporting() вернёт текущее значение уровня протоколирования ошибок.
Список параметров
Новое значение уровня error_reporting. Это может быть битовая маска или именованные константы. При использовании именованных констант нужно будет следить за совместимостью с новыми версиями PHP. В новых версиях могут добавиться новые уровни ошибок, увеличиться диапазон целочисленных типов. Все это может привести к нестабильной работе при использовании старых целочисленных обозначений уровней ошибок.
Доступные константы уровней ошибок и их описания приведены в разделе Предопределённые константы.
Возвращаемые значения
Возвращает старое значение уровня error_reporting либо текущее значение, если аргумент error_level не задан.
Список изменений
Примеры
Пример #1 Примеры использования error_reporting()
// Выключение протоколирования ошибок
error_reporting ( 0 );
// Включать в отчёт простые описания ошибок
error_reporting ( E_ERROR | E_WARNING | E_PARSE );
// Включать в отчёт E_NOTICE сообщения (добавятся сообщения о
// непроинициализированных переменных или ошибках в именах переменных)
error_reporting ( E_ERROR | E_WARNING | E_PARSE | E_NOTICE );
// Добавлять сообщения обо всех ошибках, кроме E_NOTICE
error_reporting ( E_ALL &
// Добавлять в отчёт все ошибки PHP
error_reporting ( E_ALL );
// Добавлять в отчёт все ошибки PHP
error_reporting (- 1 );
Примечания
Смотрите также
User Contributed Notes 27 notes
If you just see a blank page instead of an error reporting and you have no server access so you can’t edit php configuration files like php.ini try this:
— create a new file in which you include the faulty script:
now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.
The example of E_ALL ^ E_NOTICE is a ‘bit’ confusing for those of us not wholly conversant with bitwise operators.
If you wish to remove notices from the current level, whatever that unknown level might be, use &
(and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
The error_reporting() function won’t be effective if your display_errors directive in php.ini is set to «Off», regardless of level reporting you set. I had to set
to keep no error reporting as default, but be able to change error reporting level in my scripts.
I’m using PHP 4.3.9 and Apache 2.0.
Some E_STRICT errors seem to be thrown during the page’s compilation process. This means they cannot be disabled by dynamically altering the error level at run time within that page.
The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.
Ex, rename index.php to index.inc.php, then re-create index.php as:
( E_STRICT | E_NOTICE ));
require( ‘index.inc.php’ );
?>
That allows you to alter the error reporting prior to the file being compiled.
I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.
E_NOTICE integer value is 6135
I had the problem that if there was an error, php would just give me a blank page. Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc. But simply running the file in a different directory allowed it to show errors!
Turns out that the error_log file in the one directory was full (2.0 Gb). I erased the file and now errors are displayed normally. It might also help to turn error logging off.
this is to show all errors for code that may be run on different versions
for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL
if anyone sees any problems with it please correct this post
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.
( E_ALL );
var_dump (
error_reporting (), // value of E_ALL,
@ error_reporting () // value is 0
);
?>
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:
see more information about php 5.3 deprecated errors
If you want to see all errors in your local environment, you can set your project URL like «foo.com.local» locally and put that in bootstrap file.
error_reporting() has no effect if you have defined your own error handler with set_error_handler()
[Editor’s Note: This is not quite accurate.
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.
All other levels of errors will be passed to the custom error handler defined by set_error_handler().
Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:
Как вывести ошибки PHP на экран
При отладке скриптов на PHP обычное дело заполучить в браузере «белый экран». Что в большинстве случаев говорит об остановке выполнения PHP кода из-за ошибки. PHP интерпретатор позволяет выводить служебную информацию об ошибках на экран, что существенно облегчает отладку. Но по-умолчанию (в большинстве случаев) такое поведение из соображений безопасности отключено, то есть сообщения об ошибках PHP на экран не выводятся.
В этой статье я расскажу как заставить PHP выводить сообщения об ошибках на экран монитора в окне браузера. Инструкция справедлива для случая когда вы используете веб сервер Apache и если PHP для Вашего сайта подключен как модуль Apache.
Вывод ошибок на экран следует включать только во время отладки сайта. Наличие такого кода может негативно сказаться на безопасности веб-приложения.
Включение вывода ошибок PHP на экран в коде файла PHP
Этот способ удобен тем, что выводом ошибок на экран вы управляете в самом скрипте PHP. Параметры, заданные с помощью функции ini_set(), имеют более высокий приоритет и перекрывают директивы php.ini и .htaccess. Разместите следующий код в начале PHP файла:
Включение вывода ошибок PHP на экран с помощью файла php.ini
Этот способ актуален когда вы являетесь администратором сервера. В файле php.ini отредактируйте следующие строки (добавьте при необходимости):
Лучший способ вывода PHP ошибок на экран
На мой взгляд обычному пользователю удобнее всего использовать .htaccess, особенно если у вас больше чем один PHP файл. Способ №2 удобен для отладки одного php файла, чтобы не затрагивать уровень вывода ошибок для других php скриптов. Вариант с php.ini подойдет только администраторам сервера, но зато его действие распространяется на все сайты расположенные на данном сервере.
Благодарности
При написании статьи были использованы следующие источники: