4 Different Types of Errors in PHP
A PHP Error occurs when something is wrong in the PHP code. The error can be as simple as a missing semicolon, or as complex as calling an incorrect variable.
To efficiently resolve a PHP issue in a script, you must understand what kind of problem is occurring.
The four types of PHP errors are:
Tip: You can test your PHP scripts online. We used an online service to test the code mentioned in this article.
Warning Error
A warning error in PHP does not stop the script from running. It only warns you that there is a problem, one that is likely to cause bigger issues in the future.
The most common causes of warning errors are:
- Calling on an external file that does not exist in the directory
- Wrong parameters in a function
As there is no “external_file”, the output displays a message, notifying it failed to include it. Still, it doesn’t stop executing the script.
Notice Error
Notice errors are minor errors. They are similar to warning errors, as they also don’t stop code execution. Often, the system is uncertain whether it’s an actual error or regular code. Notice errors usually occur if the script needs access to an undefined variable.
In the script above, we defined a variable ($a), but called on an undefined variable ($b). PHP executes the script but with a notice error message telling you the variable is not defined.
Parse Error (Syntax)
Parse errors are caused by misused or missing symbols in a syntax. The compiler catches the error and terminates the script.
Parse errors are caused by:
- Unclosed brackets or quotes
- Missing or extra semicolons or parentheses
- Misspellings
For example, the following script would stop execution and signal a parse error:
It is unable to execute because of the missing semicolon in the third line.
Fatal Error
Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.
There are three (3) types of fatal errors:
- Startup fatal error (when the system can’t run the code at installation)
- Compile time fatal error (when a programmer tries to use nonexistent data)
- Runtime fatal error (happens while the program is running, causing the code to stop working completely)
For instance, the following script would result in a fatal error:
The output tells you why it is unable to compile, as in the image below:
Distinguishing between the four types of PHP errors can help you quickly identify and solve problems in your script. Make sure to pay attention to output messages, as they often report on additional issues or warnings. If you are trying to locate a bug on your website, it is also important to know which PHP version your web server is running.
Php main error types
PHP reports errors in response to a number of internal error conditions. These may be used to signal a number of different conditions, and can be displayed and/or logged as required.
Every error that PHP generates includes a type. A list of these error types is available, along with a short description of their behaviour and how they can be caused.
Handling errors with PHP
If no error handler is set, then PHP will handle any errors that occur according to its configuration. Which errors are reported and which are ignored is controlled by the error_reporting php.ini directive, or at runtime by calling error_reporting() . It is strongly recommended that the configuration directive be set, however, as some errors can occur before execution of your script begins.
In a development environment, you should always set error_reporting to E_ALL , as you need to be aware of and fix the issues raised by PHP. In production, you may wish to set this to a less verbose level such as E_ALL & ~E_NOTICE & ~E_DEPRECATED , but in many cases E_ALL is also appropriate, as it may provide early warning of potential issues.
What PHP does with these errors depends on two further php.ini directives. display_errors controls whether the error is shown as part of the script’s output. This should always be disabled in a production environment, as it can include confidential information such as database passwords, but is often useful to enable in development, as it ensures immediate reporting of issues.
In addition to displaying errors, PHP can log errors when the log_errors directive is enabled. This will log any errors to the file or syslog defined by error_log . This can be extremely useful in a production environment, as you can log errors that occur and then generate reports based on those errors.
User error handlers
If PHP’s default error handling is inadequate, you can also handle many types of error with your own custom error handler by installing it with set_error_handler() . While some error types cannot be handled this way, those that can be handled can then be handled in the way that your script sees fit: for example, this can be used to show a custom error page to the user and then report more directly than via a log, such as by sending an e-mail.
Ошибки PHP: классификация, примеры, обработка
В статье представлена очередная попытка разобраться с ошибками, которые могут встретиться на вашем пути php-разработчика, их возможная классификация, примеры их возникновения, влияние ошибок на ответ клиенту, а также инструкции по написанию своего обработчика ошибок.
Классификация ошибок
- Фатальные
Неустранимые ошибки. Работа скрипта прекращается.
E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR. - Не фатальные
Устранимые ошибки. Работа скрипта не прекращается.
E_WARNING, E_NOTICE, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING, E_USER_NOTICE, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED. - Смешанные
Фатальные, но только, если не обработаны функцией, определенной пользователем в set_error_handler().
E_USER_ERROR, E_RECOVERABLE_ERROR.
- Перехватываемые (не фатальные и смешанные)
E_USER_ERROR, E_RECOVERABLE_ERROR, E_WARNING, E_NOTICE, E_USER_WARNING, E_USER_NOTICE, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED. - Не перехватываемые (фатальные)
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING.
- Инициированы пользователем
E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE. - Инициированы PHP
E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_WARNING, E_NOTICE, E_CORE_WARNING, E_COMPILE_WARNING, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED, E_USER_ERROR, E_RECOVERABLE_ERROR.
Примеры возникновения ошибок
"; /* * перехватываемые ошибки (ловятся функцией set_error_handler()) */ // NONFATAL - E_NOTICE // echo $undefined_var; // NONFATAL - E_WARNING // array_key_exists('key', NULL); // NONFATAL - E_DEPRECATED split('[/.-]', "12/21/2012"); // split() deprecated начиная с php 5.3.0 // NONFATAL - E_STRICT // class c > c::f(); // NONFATAL - E_USER_DEPRECATED // trigger_error("E_USER_DEPRECATED", E_USER_DEPRECATED); // NONFATAL - E_USER_WARNING // trigger_error("E_USER_WARNING", E_USER_WARNING); // NONFATAL - E_USER_NOTICE // trigger_error("E_USER_NOTICE", E_USER_NOTICE); // FATAL, если не обработана функцией set_error_handler - E_RECOVERABLE_ERROR // class b > $b = new b; $b->f(NULL); // FATAL, если не обработана функцией set_error_handler - E_USER_ERROR // trigger_error("E_USER_ERROR", E_USER_ERROR); /* * неперехватываемые (не ловятся функцией set_error_handler()) */ // FATAL - E_ERROR // undefined_function(); // FATAL - E_PARSE // parse_error // FATAL - E_COMPILE_ERROR // $var[]; echo "Файл с ошибками. Конец
";
Примечание: для полной работоспособности скрипта необходим PHP версии не ниже 5.3.0.
В файле errors.php представлены выражения, инициирующие практически все возможные ошибки. Исключение составили: E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_WARNING, генерируемые ядром Zend. В теории, встретить их в реальной работе вы не должны.
В следующей таблице приведены варианты поведения этого скрипта в различных условиях (в зависимости от значений директив display_errors и error_reporting):
Группа ошибок | Значения директив * | Статус ответа сервера | Ответ клиенту ** |
---|---|---|---|
E_PARSE, E_COMPILE_ERROR *** | display_errors = off error_reporting = ANY | 500 | Пустое значение |
display_errors = on error_reporting = ANY | 200 | Сообщение об ошибке | |
E_USER_ERROR, E_ERROR, E_RECOVERABLE_ERROR | display_errors = off error_reporting = ANY | 500 | Вывод скрипта до ошибки |
display_errors = on error_reporting = ANY | 200 | Сообщение об ошибке и вывод скрипта до ошибки | |
Не фатальные ошибки | display_errors = off error_reporting = ANY и display_errors = on error_reporting = 0 | 200 | Весь вывод скрипта |
display_errors = on error_reporting = E_ALL | E_STRICT | 200 | Сообщение об ошибке и весь вывод скрипта |
* Значение ANY означает E_ALL | E_STRICT или 0.
** Ответ клиенту может отличаться от ответов на реальных скриптах. Например, вывод какой-либо информации до включения файла errors.php, будет фигурировать во всех рассмотренных случаях.
*** Если в файле errors.php заменить пример для ошибки E_COMPILE_ERROR на require «missing_file.php»; , то ошибка попадет во вторую группу.
- Наличие в файле скрипта ошибки, приводящей его в «негодное» состояние (невозможность корректно обработать), на выходе даст пустое значение или же только само сообщение об ошибке, в зависимости от значения директивы display_errors.
- Скрипт в файле с фатальной ошибкой, не относящейся к первому пункту, будет выполняться в штатном режиме до самой ошибки.
- Наличие в файле фатальной ошибки при display_errors = Off обозначит 500 статус ответа.
- Не фатальные ошибки, как и следовало ожидать, в контексте возможности исполнения скрипта в целом, на работоспособность не повлияют.
Собственный обработчик ошибок
- для получения информации о последней произошедшей ошибке существует функция error_get_last();
- для определения собственного обработчика ошибок существует функция set_error_handler(), но фатальные ошибки нельзя «перехватить» этой функцией;
- используя register_shutdown_function(), можно зарегистрировать свою функцию, выполняемую по завершении работы скрипта, и в ней, используя знания из первого пункта, если фатальная ошибка имела место быть, предпринять необходимые действия;
- сообщение о фатальной ошибке в любом случае попадет в буфер вывода;
- воспользовавшись функциями контроля вывода можно предотвратить отображение нежелательной информации;
- при использовании оператора управления ошибками (знак @) функция, определенная в set_error_handler() все равно будет вызвана, но функция error_reporting() в этом случае вернет 0, чем и можно пользоваться для прекращения работы или определения другого поведения своего обработчика ошибок.
'E_ERROR', E_WARNING => 'E_WARNING', E_PARSE => 'E_PARSE', E_NOTICE => 'E_NOTICE', E_CORE_ERROR => 'E_CORE_ERROR', E_CORE_WARNING => 'E_CORE_WARNING', E_COMPILE_ERROR => 'E_COMPILE_ERROR', E_COMPILE_WARNING => 'E_COMPILE_WARNING', E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING', E_USER_NOTICE => 'E_USER_NOTICE', E_STRICT => 'E_STRICT', E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', E_DEPRECATED => 'E_DEPRECATED', E_USER_DEPRECATED => 'E_USER_DEPRECATED', ); // выводим свое сообщение об ошибке echo " [$errno] $errstr ($errfile на $errline строке)
\n"; > // не запускаем внутренний обработчик ошибок PHP return TRUE; > /** * Функция перехвата фатальных ошибок */ function fatal_error_handler() < // если была ошибка и она фатальна if ($error = error_get_last() AND $error['type'] & ( E_ERROR | E_PARSE | E_COMPILE_ERROR | E_CORE_ERROR)) < // очищаем буффер (не выводим стандартное сообщение об ошибке) ob_end_clean(); // запускаем обработчик ошибок error_handler($error['type'], $error['message'], $error['file'], $error['line']); >else < // отправка (вывод) буфера и его отключение ob_end_flush(); >> // определеяем уровень протоколирования ошибок error_reporting(E_ALL | E_STRICT); // определяем режим вывода ошибок ini_set('display_errors', 'On'); // включаем буфферизацию вывода (вывод скрипта сохраняется во внутреннем буфере) ob_start(); // устанавливаем пользовательский обработчик ошибок set_error_handler("error_handler"); // регистрируем функцию, которая выполняется после завершения работы скрипта (например, после фатальной ошибки) register_shutdown_function('fatal_error_handler'); require 'errors.php';
Не забываем, что ошибки смешанного типа, после объявления собственного обработчика ошибок, стали не фатальными. Плюс к этому, весь вывод скрипта до фатальной ошибки вместе с стандартным сообщением об ошибке будет сброшен.
Вообще, рассмотренный пример обработчика ошибок, обработкой, как таковой, не занимается, а только демонстрирует саму возможность. Дальнейшее его поведение зависит от ваших желаний и/или требований. Например, все случаи обращения к обработчику можно записывать в лог, а в случае фатальных ошибок, дополнительно, уведомлять об этом администратора ресурса.
Полезные ссылки
- Первоисточник: php.net/manual/ru/book.errorfunc.php
- Описание ошибок: php.net/manual/ru/errorfunc.constants.php
- Функции контроля вывода: php.net/manual/ru/ref.outcontrol.php
- Побитовые операторы: php.net/manual/ru/language.operators.bitwise.php и habrahabr.ru/post/134557
- Тематически близкая статья: habrahabr.ru/post/134499