(PHP 4, PHP 5, PHP 7, PHP 8)
error_reporting —
Задаёт, какие ошибки PHP попадут в отчёт
Описание
error_reporting(?int $error_level = null): int
Список параметров
-
error_level -
Новое значение уровня
error_reporting. Это может
быть битовая маска или именованные константы. При использовании
именованных констант нужно будет следить за совместимостью с новыми
версиями PHP. В новых версиях могут добавиться новые уровни ошибок,
увеличиться диапазон целочисленных типов. Все это может привести к
нестабильной работе при использовании старых целочисленных обозначений
уровней ошибок.Доступные константы уровней ошибок и их описания приведены в разделе
Предопределённые константы.
Возвращаемые значения
Возвращает старое значение уровня
error_reporting либо текущее
значение, если аргумент error_level не задан.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 |
error_level теперь допускает значение null.
|
Примеры
Пример #1 Примеры использования error_reporting()
<?php// Выключение протоколирования ошибок
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 & ~E_NOTICE);// Добавлять в отчёт все ошибки PHP
error_reporting(E_ALL);// Добавлять в отчёт все ошибки PHP
error_reporting(-1);// То же, что и error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>
Примечания
Подсказка
Если передать -1, будут отображаться все возможные
ошибки, даже если в новых версиях PHP добавятся уровни или константы.
Поведение эквивалентно передаче константы E_ALL.
info at hephoz dot de ¶
14 years ago
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:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
- execute this file instead of the faulty script file
now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
jcastromail at yahoo dot es ¶
2 years ago
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.
For example
<?php
$a
=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8?>
dave at davidhbrown dot us ¶
16 years ago
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 & ~ instead:
<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>
^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
Fernando Piancastelli ¶
18 years ago
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
display_errors = On
error_reporting = ~E_ALL
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.
lhenry at lhenry dot com ¶
3 years ago
In php7, what was generally a notice or a deprecated is now a warning : the same level of a mysql error … unacceptable for me.
I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.
So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING
Custom overriding the level of php errors should be super handy and flexible …
luisdev ¶
4 years ago
This article refers to these two reporting levels:
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
What is the difference between those two levels?
Please update this article with a clear explanation of the difference and the possible use cases.
ecervetti at orupaca dot fr ¶
13 years ago
It could save two minutes to someone:
E_ALL & ~E_NOTICE integer value is 6135
qeremy ! gmail ¶
7 years ago
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.
<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
// or error_reporting(E_ALL);
}
?>
Rash ¶
8 years ago
If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.
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.
chris at ocproducts dot com ¶
6 years ago
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
keithm at aoeex dot com ¶
12 years ago
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:
<?php
error_reporting(E_ALL & ~(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.
huhiko334 at yandex dot ru ¶
4 years ago
If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct
kevinson112 at yahoo dot com ¶
4 years ago
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.
https://techysupport.co/norton-tech-support/
adam at adamhahn dot com ¶
5 years ago
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.
<?php
error_reporting(E_ALL);
var_dump(
error_reporting(), // value of E_ALL,
@error_reporting() // value is 0
);
?>
kc8yds at gmail dot com ¶
14 years ago
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
<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
vdephily at bluemetrix dot com ¶
17 years ago
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);$foo = $bar; //notice : $bar uninitialized$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok$foo = $bar['nope'] // notice : no such index
?>
fredrik at demomusic dot nu ¶
17 years ago
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".
This is very useful to remember when setting error_reporting levels in httpd.conf:
Use the table above or:
<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>
To get the appropriate integer for your error-level. Then use:
php_admin_value error_reporting YOUR_INT
in httpd.conf
I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...
Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
rojaro at gmail dot com ¶
12 years ago
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:
<?php error_reporting(-1); ?>
j dot schriver at vindiou dot com ¶
22 years ago
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:
if (!($type & error_reporting())) return;
-zak@php.net]
teynon1 at gmail dot com ¶
10 years ago
It might be a good idea to include E_COMPILE_ERROR in error_reporting.
If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.
Example:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function
myErrorHandler($errno, $errstr, $errfile, $errline) {
// Do something other than output message.
return true;
}$old_error_handler = set_error_handler("myErrorHandler");
require
"this file does not exist";
?>
To prevent this, simply include E_COMPILE_ERROR in the error_reporting.
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
misplacedme at gmail dot com ¶
13 years ago
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>
I made this function to make things a little bit quicker. Unset values passed by reference won't trigger a notice.
<?php
function test_ref(&$var,$test_function='',$negate=false) {
$stat = true;
if(!isset($var)) $stat = false;
if (!empty($test_function) && function_exists($test_function)){
$stat = $test_function($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif($test_function == 'empty') {
$stat = empty($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif (!function_exists($test_function)) {
$stat = false;
trigger_error("$test_function() is not a valid function");
}
$stat = ($stat) ? true : false;
return $stat;
}
$a = '';
$b = '15';test_ref($a,'empty',true); //False
test_ref($a,'is_int'); //False
test_ref($a,'is_numeric'); //False
test_ref($b,'empty',true); //true
test_ref($b,'is_int'); //False
test_ref($b,'is_numeric'); //false
test_ref($unset,'is_numeric'); //false
test_ref($b,'is_number'); //returns false, with an error.
?>
Alex ¶
16 years ago
error_reporting() may give unexpected results if the @ error suppression directive is used.
<?php
@include 'config.php';
include 'foo.bar'; // non-existent file
?>
config.php
<?php
error_reporting(0);
?>
will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings). If the suppressor is removed, this works as expected.
Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result. This is contrary to the note above which says that the two instructions are equivalent.
Daz Williams (The Northeast) ¶
13 years ago
Only display php errors to the developer...
<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
ini_set('display_errors','On');
}
else
{
ini_set('display_errors','Off');
}
?>
Just replace 00.00.00.00 with your ip address.
forcemdt ¶
9 years ago
Php >5.4
Creating a Custom Error Handler
set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
DarkGool ¶
17 years ago
In phpinfo() error reporting level display like a bit (such as 4095)
Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file
<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
$end = $i;
}
$res[] = $end;
$bit = $bit - $end;
}
?>
In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8) // E_NOTICE
...
&IT ¶
2 years ago
error_reporting(E_ALL);
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
За уровень обработки ошибок в PHP отвечает директива error_reporting конфигурационного файла php.ini. Данный параметр определяет типы ошибок, о которых PHP информирует выводом текстового сообщения в окно браузера.
Возможные значения директивы
| Уровень ошибки | Константа | Описание ошибки |
|---|---|---|
| 1 | E_ERROR | Ошибки обычных функций (критичные ошибки) |
| 2 | E_WARNING | Обычные предупреждения (не критичные ошибки) |
| 4 | E_PARSE | Ошибки синтаксического анализатора |
| 8 | E_NOTICE | Замечания (аномалии в коде, возможные источники ошибок — следует отключить при наличии русского текста в коде, так как для интернациональных кодировок не обеспечивается корректная работа). |
| 16 | E_CORE_ERROR | Ошибки обработчика |
| 32 | E_CORE_WARNING | Предупреждения обработчика |
| 64 | E_COMPILE_ERROR | Ошибки компилятора |
| 128 | E_COMPILE_WARNING | Предупреждения компилятора |
| 256 | E_USER_ERROR | Ошибки пользователей |
| 512 | E_USER_WARNING | Предупреждения пользователей |
| 1024 | E_USER_NOTICE | Уведомления пользователей |
| E_ALL | Все ошибки |
Вышеуказанные значения (цифровые или символьные) используются для построения битовой маски, которая специфицирует выводимое сообщение об ошибке. Вы можете использовать битовые операции для маскирования определённых типов ошибок. Обратите внимание, что только ‘|’, ‘~’, ‘!’ и ‘&’ будут понятны в php.ini и что никакие битовые операции не будут понятны в php3.ini.
В PHP 4 значением по умолчанию для error_reporting будет E_ALL & ~E_NOTICE, что означает отображение всех ошибок и предупреждений, которые не имеют уровень E_NOTICE-level. В PHP 3 значение по умолчанию — E_ERROR | E_WARNING | E_PARSE означает то же самое.
Заметьте, однако, что, поскольку константы не поддерживаются в PHP 3 в файле php3.ini, установка error_reporting должна выполняться цифрами; то есть 7 по умолчанию.
Настройка при помощи php.ini
Параметр error_reporting позволяет устанавливать несколько уровней, используя побитовые флаги. К примеру, уровень:
error_reporting = E_ALL & ~E_NOTICE
позволяет выводить все ошибки, за исключением замечаний.
А для того чтобы показывать только ошибки (исключая предупреждения и замечания), директива должна быть настроена так, как показано ниже:
error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR
Настройка при помощи .htaccess
Включаем вывод ошибок в окно браузера и устанавливаем нужный уровень.
<br /> php_flag display_errors On<br /> php_value error_reporting E_ALL<br />
Настройка при помощи PHP
Включаем вывод ошибок в окно браузера и устанавливаем нужный уровень.
<?php
error_reporting(E_ALL);
ini_set("display_error", true);
ini_set("error_reporting", E_ALL);
?>
Ссылки
- Функция error_reporting
- Директива error_reporting файла php.ini
PHP Документация
Настройка во время выполнения
Поведение этих функций зависит от установок в php.ini.
| Имя | По умолчанию | Место изменения | Список изменений |
|---|---|---|---|
| error_reporting | NULL | PHP_INI_ALL | |
| display_errors | «1» | PHP_INI_ALL | |
| display_startup_errors | «1» | PHP_INI_ALL |
До PHP 8.0.0 значение по умолчанию было "0".
|
| log_errors | «0» | PHP_INI_ALL | |
| log_errors_max_len | «1024» | PHP_INI_ALL | |
| ignore_repeated_errors | «0» | PHP_INI_ALL | |
| ignore_repeated_source | «0» | PHP_INI_ALL | |
| report_memleaks | «1» | PHP_INI_ALL | |
| track_errors | «0» | PHP_INI_ALL | Объявлено устаревшим в PHP 7.2.0, удалено в PHP 8.0.0. |
| html_errors | «1» | PHP_INI_ALL | |
| xmlrpc_errors | «0» | PHP_INI_SYSTEM | |
| xmlrpc_error_number | «0» | PHP_INI_ALL | |
| docref_root | «» | PHP_INI_ALL | |
| docref_ext | «» | PHP_INI_ALL | |
| error_prepend_string | NULL | PHP_INI_ALL | |
| error_append_string | NULL | PHP_INI_ALL | |
| error_log | NULL | PHP_INI_ALL | |
| error_log_mode | 0o644 | PHP_INI_ALL | Доступно, начиная с PHP 8.2.0 |
| syslog.facility | «LOG_USER» | PHP_INI_SYSTEM | Доступно, начиная с PHP 7.3.0. |
| syslog.filter | «no-ctrl» | PHP_INI_ALL | Доступно, начиная с PHP 7.3.0. |
| syslog.ident | «php» | PHP_INI_SYSTEM | Доступно, начиная с PHP 7.3.0. |
Для подробного описания констант
PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.
Краткое разъяснение конфигурационных
директив.
-
error_reporting
int -
Задаёт уровень протоколирования ошибки. Параметр может быть либо числом,
представляющим битовое поле, либо именованной константой.
Соответствующие уровни и константы приведены в разделе
Предопределённые константы,
а также в php.ini. Для установки настройки во время выполнения используйте функцию
error_reporting(). Смотрите также описание директивы
display_errors.Значение по умолчанию равно
E_ALL.До PHP 8.0.0 значение по умолчанию было:
.E_ALL&
~E_NOTICE&
~E_STRICT&
~E_DEPRECATED
При этой настройке не отображаются уровни ошибокE_NOTICE,
E_STRICTиE_DEPRECATED.Замечание:
PHP-константы за пределами PHPИспользование PHP-констант за пределами PHP, например в файле
httpd.conf, не имеет смысла, так как в таких случаях требуются
целочисленные значения (int). Более того, с течением времени будут
добавляться новые уровни ошибок, а максимальное значение константы
E_ALLсоответственно будет расти. Поэтому в месте, где
предполагается указатьE_ALL, лучше задать большое целое число,
чтобы перекрыть все возможные битовые поля. Таким числом может быть, например,
2147483647(оно включит все возможные ошибки, не
толькоE_ALL). -
display_errors
string -
Эта настройка определяет, требуется ли выводить ошибки на экран вместе
с остальным выводом, либо ошибки должны быть скрыты от пользователя.Значение
"stderr"посылает ошибки в потокstderr
вместоstdout.Замечание:
Эта функциональность предназначена только для разработки и не должен использоваться в
готовых производственных системах (например, системах, имеющих доступ в интернет).Замечание:
Несмотря на то, что display_errors может быть установлена во время выполнения
(функцией ini_set()), это ни на что не повлияет, если в скрипте есть
фатальные ошибки. Это обусловлено тем, что ожидаемые действия программы во время
выполнения не получат управления (не будут выполняться). -
display_startup_errors
bool -
Даже если display_errors включена, ошибки, возникающие во время запуска PHP, не будут
отображаться. Настойчиво рекомендуем включать директиву display_startup_errors только
для отладки. -
log_errors
bool -
Отвечает за выбор журнала, в котором будут сохраняться сообщения об ошибках. Это
может быть журнал сервера или error_log.
Применимость этой настройки зависит от конкретного сервера.Замечание:
Настоятельно рекомендуем при работе на готовых работающих
web сайтах протоколировать ошибки там, где они отображаются. -
log_errors_max_len
int -
Задание максимальной длины log_errors в байтах. В
error_log добавляется информация
об источнике. Значение по умолчанию 1024. Установка значения в 0
позволяет снять ограничение на длину log_errors. Это ограничение
распространяется на записываемые в журнал ошибки, на отображаемые ошибки,
а также на $php_errormsg, но не на явно вызываемые функции,
такие как error_log().Если используется int, значение измеряется байтами. Вы также можете использовать сокращённую запись, которая описана в этом разделе FAQ.
-
ignore_repeated_errors
bool -
Не заносить в журнал повторяющиеся ошибки. Ошибка считается
повторяющейся, если происходит в том же файле и в той же строке, и если настройка
ignore_repeated_source выключена. -
ignore_repeated_source
bool -
Игнорировать источник ошибок при пропуске повторяющихся сообщений. Когда
эта настройка включена, повторяющиеся сообщения об ошибках не будут
заноситься в журнал вне зависимости от того, в каких файлах и строках они происходят. -
report_memleaks
bool -
Если настройка включена (по умолчанию), будет формироваться отчёт об утечках памяти,
зафиксированных менеджером памяти Zend. На POSIX платформах этот отчёт будет
направляться в поток stderr. На Windows платформах он будет посылаться в отладчик
функцией OutputDebugString(), просмотреть отчёт в этом случае можно с помощью утилит,
вроде » DbgView. Эта настройка имеет
смысл в сборках, предназначенных для отладки. При этом
E_WARNINGдолжна быть включена в список error_reporting. -
track_errors
bool -
Если включена, последняя произошедшая ошибка будет первой в переменной
$php_errormsg. -
html_errors
bool -
Если разрешена, сообщения об ошибках будут включать теги HTML. Формат для
HTML-ошибок производит нажимаемые ссылки, ведущие на описание ошибки, либо
функии, в которой она произошла. За такие ссылки ответственны
docref_root и
docref_ext.Если запрещена, то ошибки будут выдаваться простым текстом, без форматирования.
-
xmlrpc_errors
bool -
Если включена, то нормальное оповещение об ошибках отключается и, вместо него,
ошибки выводятся в формате XML-RPC. -
xmlrpc_error_number
int -
Используется в качестве значения XML-RPC элемента faultCode.
-
docref_root
string -
Новый формат ошибок содержит ссылку на страницу с описанием ошибки или
функции, вызвавшей эту ошибку. Можно разместить копию
описаний ошибок и функций локально и задать ini директиве значение
URL этой копии. Если, например, локальная копия описаний доступна по
адресу"/manual/", достаточно прописать
docref_root=/manual/. Дополнительно, необходимо
задать значение директиве docref_ext, отвечающей за соответствие
расширений файлов файлам описаний вашей локальной копии,
docref_ext=.html. Также возможно использование
внешних ссылок. Например,
docref_root=http://manual/en/или
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"В большинстве случаев вам потребуется, чтобы значение docref_root оканчивалось
слешем"/". Тем не менее, бывают случаи, когда
это не требуется (смотрите выше, второй пример).Замечание:
Эта функциональность предназначена только для разработки, так как он облегчает
поиск описаний функций и ошибок. Не используйте его в готовых
производственных системах (например, имеющих доступ в интернет). -
docref_ext
string -
Смотрите docref_root.
Замечание:
Значение docref_ext должно начинаться с точки
".". -
error_prepend_string
string -
Строка, которая будет выводиться непосредственно перед сообщением об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке. -
error_append_string
string -
Строка, которая будет выводиться после сообщения об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке. -
error_log
string -
Имя файла, в который будут добавляться сообщения об ошибках. Файл
должен быть открыт для записи пользователем веб-сервера. Если
используется специальное значениеsyslog, то
сообщения будут посылаться в системный журнал. На Unix-системах это
syslog(3), на Windows NT — журнал событий. Смотрите также: syslog().
Если директива не задана, ошибки будут направляться в SAPI журналы.
Например, это могут быть журналы ошибок Apache или поток
stderrкомандной строки CLI.
Смотрите также функцию error_log(). -
error_log_mode
int -
Режим файла, описанного в error_log.
-
syslog.facility
string -
Указывает, какой тип программы регистрирует сообщение.
Действует только в том случае, если опция error_log установлена в «syslog». -
syslog.filter
string -
Указывает тип фильтра для фильтрации регистрируемых сообщений.
Разрешённые символы передаются без изменений; все остальные записываются в шестнадцатеричном представлении с префиксомx.-
all– строка будет разделена
на символы новой строки и все символы будут переданы без изменений
-
ascii– строка будет разделена
на символы новой строки, а любые непечатаемые 7-битные символы ASCII будут экранированы
-
no-ctrl– строка будет разделена
на символы новой строки, а любые непечатаемые символы будут экранированы
-
raw– все символы передаются в системный
журнал без изменений, без разделения на новые строки (идентично PHP до 7.3)
Параметр влияет на ведение журнала через error_log установленного в «syslog» и вызовы syslog().
Замечание:
Тип фильтра
rawдоступен начиная с PHP 7.3.8 и PHP 7.4.0.
Директива не поддерживается в Windows.
-
-
syslog.ident
string -
Определяет строку идентификатора, которая добавляется к каждому сообщению.
Действует только в том случае, если опция error_log установлена в «syslog».
cjakeman at bcs dot org ¶
13 years ago
Using
<?php ini_set('display_errors', 1); ?>
at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.
This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set
display_errors On
then there is a possible solution suggested under error_reporting:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
[Modified by moderator]
You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).
ohcc at 163 dot com ¶
6 years ago
If you set the error_log directive to a relative path, it is a path relative to the document root rather than php's containing folder.
Roger ¶
3 years ago
When `error_log` is set to a file path, log messages will automatically be prefixed with timestamp [DD-MMM-YYYY HH:MM:SS UTC]. This appears to be hard-coded, with no formatting options.
php dot net at sp-in dot dk ¶
8 years ago
There does not appear to be a way to set a tag / ident / program for log entries in the ini file when using error_log=syslog. When I test locally, "apache2" is used.
However, calling openlog() with an ident parameter early in your script (or using an auto_prepend_file) will make PHP use that value for all subsequent log entries. closelog() will restore the original tag.
This can be done for setting facility as well, although the original value does not seem to be restored by closelog().
iio7 at protonmail dot com ¶
1 year ago
It's important to note that when display_errors is "on", PHP will send a HTTP 200 OK status code even when there is an error. This is not a mistake or a wrong behavior, but is because you're asking PHP to output normal HTML, i.e. the error message, to the browser.
When display_errors is set to "off", PHP will send a HTTP 500 Internal Server Error, and let the web server handle it from there. If the web server is setup to intercept FastCGI errors (in case of NGINX), it will display the 500 error page it has setup. If the web server cannot intercept FastCGI errors, or it isn't setup to do it, an empty screen will be displayed in the browser (the famous white screen of death).
If you need a custom error page but cannot intercept PHP errors on the web server you're using, you can use PHPs custom error and exception handling mechanism. If you combine that with output buffering you can prevent any output to reach the client before the error/exception occurs. Just remember that parse errors are compile time errors that cannot be handled by a custom handler, use "php -l foo.php" from the terminal to check for parse errors before putting your files on production.
jaymore at gmail dot com ¶
6 years ago
Document says
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).
But it is better to set "-1" as the E_ALL value.
For example, in httpd.conf or .htaccess, use
php_value error_reporting -1
to report all kind of error without be worried by the PHP version.
На чтение 11 мин Просмотров 1.2к. Опубликовано 16.10.2021
PHP существует довольно давно и разработал свои особенности и особенности. Он также разработал свой собственный вид отчетов об ошибках, который довольно прост. В этом посте мы покажем вам, как легко добавить мониторинг ошибок для PHP.
Содержание
- Что такое ошибка PHP?
- Какие бывают типы ошибок в PHP?
- Ошибки синтаксического анализа или синтаксиса
- Фатальные ошибки
- Предупреждение об ошибках
- Уведомление об ошибках
- Как включить отчеты об ошибках в PHP
- Сколько уровней ошибок доступно в PHP?
- Ошибки отображения PHP
- Что такое предупреждение PHP?
- Как помогают отчеты о сбоях
- Завершение отчета об ошибках PHP
Что такое ошибка PHP?
Ошибка PHP — это структура данных, представляющая что-то, что пошло не так в вашем приложении. В PHP есть несколько конкретных способов вызова ошибок. Один из простых способов имитировать ошибку — использовать die()функцию:
die("something bad happened!");
Это завершит программу PHP и сообщит об ошибке. Когда программа завершается, это то, что мы называем фатальной ошибкой. Позже вы увидите, что мы можем контролировать, как именно обрабатывается ошибка, в случае, если нам нужно вызвать некоторую логику очистки или перенаправить сообщение об ошибке. Вы также можете смоделировать это с помощью trigger_error()функции:
<?php trigger_error("something happened"); //error level is E_USER_NOTICE //You can control error level trigger_error("something bad happened", E_USER_ERROR); ?>
По умолчанию это вызовет в системе некритическое уведомление. Вы можете переопределить уровень ошибки, если вам нужна более серьезная ошибка.
На самом деле в PHP есть две формы ошибок: стандартные обычные ошибки и исключения.
Исключения были введены в PHP 5. Они дают вам легче семантику, как try, throwи catch. Исключение легко создать. Это следует из большого успеха языков со статической типизацией, таких как C # и Java.
throw new Exception("Yo, something exceptional happened);
Перехват и выдача исключений, как правило, более упрощены, чем более традиционная обработка ошибок PHP. Вы также можете иметь более локализованную обработку ошибок, а не только глобальную обработку ошибок с помощью set_error_handler (). Вы можете окружить конкретную логику блоками try / catch, которые заботятся только о конкретных исключениях:
<?php try { doSystemLogic(); } catch (SystemException $e) { echo 'Caught system exception '; } try { doUserLogic(); } catch (Exception $e) { echo 'Caught misc exception '; } ?>
Какие бывают типы ошибок в PHP?
Ошибка PHP — это не одно и то же, но бывает четырех разных типов:
- синтаксические или синтаксические ошибки
- фатальные ошибки
- предупреждения об ошибках
- замечать ошибки
Ошибки синтаксического анализа или синтаксиса
Первая категория ошибок в PHP — это ошибки синтаксического анализа, также называемые синтаксическими ошибками. Они просто означают, что в вашем скрипте есть один или несколько неправильных символов. Возможно, вы пропустили точку с запятой или неправильно поставили скобку. Взгляните на следующий пример:
<?php $age = 25; if ($age >= 18 { echo 'Of Age'; } else { echo 'Minor'; } ?>
Запустив приведенный выше сценарий, я получаю следующую ошибку:
Parse error: syntax error, unexpected '{' in <path> on line 4
С помощью сообщения об ошибке легко увидеть, что в операторе if отсутствует закрывающая скобка. Давайте исправим это:
<?php $age = 25; if ($age >= 18) { echo 'Of Age'; } else { echo 'Minor'; } ?>
Фатальные ошибки
Неустранимые ошибки, как следует из их названия, — это те, которые способны убить — или привести к сбою — приложение. Другими словами, фатальные ошибки — это критические ошибки, означающие, что произошло что-то катастрофическое, и приложение не может продолжать работу.
Часто причиной фатальных ошибок является неопределенный класс, функция или другой артефакт. Если сценарий пытается использовать несуществующую функцию, PHP не знает, что делать, и сценарий необходимо остановить.
Рассмотрим следующий сценарий:
<?php function add($a, $b) { return $a + $b; } echo '2 + 2 is ' . sum(2, 2); ?>
Как видите, сценарий определяет функцию с именем add, а затем пытается вызвать ее с неправильным именем. Эта ситуация приводит к фатальной ошибке:
Fatal error: Uncaught Error: Call to undefined function sum() in F:xampphtdocstest.php:7 Stack trace: #0 {main} thrown in <path> on line 7
Все, что нужно для решения ошибки, — это изменить вызов функции на правильное имя, добавить:
echo '2 + 2 is ' . add(2, 2);
Предупреждение об ошибках
Предупреждающие ошибки — это ошибки, которые не приводят к завершению работы скрипта. Подобно тому, что происходит на других языках, предупреждение в PHP обычно представляет собой что-то, что еще не является серьезной проблемой — или, по крайней мере, не критичной, — но может стать серьезной проблемой в будущем, поэтому вам лучше сохранить глаз на это.
Взгляните на следующий код:
<?php $components = parse_url(); var_dump($components); ?>
После выполнения приведенного выше кода мы получаем следующее предупреждение:
Warning: parse_url() expects at least 1 parameter, 0 given in <path> on line 2
Предупреждение вызывает тот факт, что мы не предоставили параметр функции parse_url. Давайте исправим это:
<?php $components = parse_url('https://example.com'); var_dump($components); ?>
Это устраняет предупреждение:
array(2) { ["scheme"]=> string(5) "https" ["host"]=> string(11) "example.com" }
Уведомление об ошибках
Уведомления об ошибках похожи на предупреждения в том, что они также не останавливают выполнение скрипта. Вы также должны думать об ошибках уведомления как о том, что PHP предупреждает вас о том, что может стать проблемой в будущем. Однако уведомления обычно считаются менее важными или менее важными, чем предупреждения.
Рассмотрим следующий фрагмент кода, который представляет собой измененную версию сценария, использованного в предыдущих разделах:
<?php $numbers = "1,2,5,6"; $parts = explode(",", $integers); echo 'The first number is ' . $parts[0]; ?>
Как видите, сценарий определяет переменную $ numbers, а затем пытается передать переменную с именем $ inteers в функцию explode.
Неопределенные переменные действительно являются одной из основных причин уведомлений в PHP. Чтобы ошибка исчезла, достаточно изменить переменную $ inteers на $ numbers.
Как включить отчеты об ошибках в PHP
Включить отчеты об ошибках в PHP очень просто. Вы просто вызываете функцию в своем скрипте:
<?php error_reporting(E_ALL); //You can also report all errors by using -1 error_reporting(-1); //If you are feeling old school ini_set('error_reporting', E_ALL); ?>
Здесь сказано: «Пожалуйста, сообщайте об ошибках всех уровней». Мы рассмотрим, какие уровни есть позже, но считаем это категорией ошибок. По сути, он говорит: «Сообщайте обо всех категориях ошибок». Вы можете отключить отчет об ошибках, установив 0:
<?php error_reporting(0); ?>
Параметр метода в error_reporting()действительности является битовой маской. Вы можете указать в нем различные комбинации уровней ошибок, используя эту маску, как видите:
<?php error_reporting(E_ERROR | E_WARNING | E_PARSE); ?>
В нем говорится: «сообщать о фатальных ошибках, предупреждениях и ошибках синтаксического анализатора». Вы можете просто разделить их знаком «|» чтобы добавить больше ошибок. Иногда вам могут потребоваться более расширенные настройки отчетов об ошибках. Вы можете использовать операторы битовой маски для составления отчетов по различным критериям:
<?php // Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); ?>
Как видите, вы можете гибко определять, о каких ошибках сообщать. Возникает вопрос: о каких типах ошибок и исключений следует сообщать?
Сколько уровней ошибок доступно в PHP?
В PHP 5 целых 16 уровней ошибок. Эти ошибки представляют категорию, а иногда и серьезность ошибки в PHP. Их много, но многочисленные категории позволяют легко определить, где отлаживать ошибку, исходя только из ее уровня. Итак, если вы хотите сделать что-то конкретное только для ошибок пользователя, например, проверку ввода, вы можете определить обработчик условий для всего, что начинается с E_USER. Если вы хотите убедиться, что вы закрыли ресурс, вы можете сделать это, указав на ошибки, оканчивающиеся на _ERROR.
Ошибки в PHP по большей части классифицируются по степени серьезности (предупреждение об ошибке, уведомление) и источнику (пользователь, компилятор, среда выполнения).
Я хочу остановиться на нескольких популярных из них.
Во-первых, у нас есть общие ошибки:
- E_ERROR (значение 1): это типичная фатальная ошибка. Если вы видите этого плохого парня, ваше приложение готово. Перезагрузите и попробуйте еще раз.
- E_WARNING (2): это ошибки, которые не приводят к сбою вашего приложения. Похоже, что большинство ошибок находятся на этом уровне.
Далее у нас есть пользовательские ошибки:
- E_USER_ERROR (256): созданная пользователем версия указанной выше фатальной ошибки. Это часто создается с помощью trigger_error ().
- E_USER_NOTICE (1024): созданная пользователем версия информационного события. Обычно это не оказывает неблагоприятного воздействия на приложение, как и log.info ().
Последняя категория, на которую следует обратить внимание, — это ошибки жизненного цикла приложения, обычно с «core» или «compile» в названии:
- EE_CORE_ERROR (16): Подобно фатальным ошибкам выше, эта ошибка может возникнуть только при запуске приложения PHP.
- EE_COMPILE_WARNING (128): нефатальная ошибка, которая возникает только тогда, когда скрипт PHP не компилируется.
Есть еще несколько ошибок. Вы можете найти их полный список здесь.
Ошибки отображения PHP
Отображение сообщений об ошибках в PHP часто сбивает с толку. Просто погуглите «Отображение сообщения об ошибке PHP» и посмотрите. Почему так?
В PHP вы можете решить, отображать ли ошибки или нет. Это отличается от сообщения о них. Сообщение о них гарантирует, что ошибки не будут проглочены. Но отображение их покажет их пользователю. Вы можете настроить отображение всех ошибок PHP с помощью директив display_errors и display_startup_errors:
<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); ?>
Их включение гарантирует, что они будут отображаться в теле веб-ответа пользователю. Обычно рекомендуется отключать их в среде, не связанной с разработкой. Целочисленный параметр метода также является битовой маской, как в error_reporting(). Здесь также применяются те же правила и параметры для этого параметра.
Что такое предупреждение PHP?
Выше вы заметили, что одним из уровней ошибок является E_WARNING. Вы также могли заметить, что многие уровни ошибок имеют версии предупреждений. Я хочу немного в этом разобраться. Основное различие между предупреждением и ошибкой в PHP заключается в том, завершает ли оно приложение. В PHP большинство ошибок фактически не останавливают выполнение скрипта.
Вот пример:
<?php $x = 1; trigger_error("user warning!", E_USER_WARNING); $x = 3; echo "$x is ${$x}"; ?>
Вы все равно будете видеть, $x is 3несмотря на срабатывание предупреждения. Это может быть полезно, если вы хотите собрать список ошибок проверки. Я лично предпочитаю использовать исключения в наши дни, но ваш опыт может отличаться.
Конечно, вы можете настроить отображение предупреждений PHP или нет. Для этого вы должны использовать конфигурацию display_errors, которую вы видели в предыдущем разделе.
Как помогают отчеты о сбоях
PHP упрощает настройку внешних инструментов отчетов об ошибках, подобных тем, которые предлагает Raygun. Он предоставляет несколько различных ловушек для своей среды выполнения, чтобы обрабатывать ошибки и отправлять их по сети. См. Этот пример, взятый со страницы PHP Raygun :
namespace { // paste your 'requires' statement $client = new Raygun4phpRaygunClient("apikey for your application"); function error_handler($errno, $errstr, $errfile, $errline ) { global $client; $client->SendError($errno, $errstr, $errfile, $errline); } function exception_handler($exception) { global $client; $client->SendException($exception); } set_exception_handler('exception_handler'); set_error_handler("error_handler"); }
Сначала мы объявляем клиента, используя ключ API для безопасности:
$client = new Raygun4phpRaygunClient("apikey for your application");
Затем мы создаем пару функций, которые обрабатывают наши ошибки и исключения:
function error_handler($errno, $errstr, $errfile, $errline ) { global $client; $client->SendError($errno, $errstr, $errfile, $errline); } function exception_handler($exception) { global $client; $client->SendException($exception); }
Обратите внимание, что мы вызываем SendError()функцию, передавая некоторые важные сведения о структуре данных ошибки. Это сделает удаленный вызов Raygun.
Наконец, мы подключаем их к среде выполнения PHP, глобально обрабатывая как традиционные ошибки, так и новые исключения:
set_exception_handler('exception_handler'); set_error_handler("error_handler");
Вот и все. Имея все это на месте, мы можем получить красиво отформатированный отчет об ошибках, который может выглядеть следующим образом:
Завершение отчета об ошибках PHP
Как видите, отчеты об ошибках PHP просты. Вы можете инициировать исключения с помощью специальных функций. Вы также можете запускать исключения, как и в других типизированных языках.
Также вы можете легко подключить свои собственные обработчики и управлять отчетностью и отображением ошибок. Это позволяет нам подключить инструмент Raygun без особых усилий — не стесняйтесь подписаться на пробную версию Raygun и добавить ее в свое приложение за считанные минуты.
error_reporting
(PHP 4, PHP 5, PHP 7)
error_reporting —
Задает, какие ошибки PHP попадут в отчет
Описание
int error_reporting
([ int $level
] )
Список параметров
-
level -
Новое значение уровня
error_reporting. Это может
быть битовая маска или именованные константы. При использовании
именованных констант нужно будет следить за совместимостью с новыми
версиями PHP. В новых версиях могут добавиться новые уровни ошибок,
увеличиться диапазон целочисленных типов. Все это может привести к
нестабильной работе при использовании старых целочисленных обозначений
уровней ошибок.Доступные константы уровней ошибок и их описания приведены в разделе
Предопределенные константы.
Возвращаемые значения
Возвращает старое значение уровня
error_reporting либо текущее
значение, если аргумент level не задан.
Список изменений
| Версия | Описание |
|---|---|
| 5.4.0 | E_STRICT стал частьюE_ALL.
|
| 5.3.0 |
Добавлены E_DEPRECATED иE_USER_DEPRECATED.
|
| 5.2.0 |
Добавлена E_RECOVERABLE_ERROR.
|
| 5.0.0 |
Добавлена E_STRICT (не входит в составE_ALL).
|
Примеры
Пример #1 Примеры использования error_reporting()
<?php// Выключение протоколирования ошибок
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 & ~E_NOTICE);// Добавлять в отчет все PHP ошибки (см. список изменений)
error_reporting(E_ALL);// Добавлять в отчет все PHP ошибки
error_reporting(-1);// То же, что и error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>
Примечания
Внимание
Большинство E_STRICT ошибок отлавливаются на этапе
компиляции, поэтому такие ошибки не включаются в отчет в файлах, где
error_reporting расширен для
включения E_STRICT ошибок (и наоборот).
Подсказка
Если передать -1, будут отображаться все возможные
ошибки, даже если в новых версиях PHP добавятся уровни или константы. В
версии PHP 5.4. передача константы E_ALL дает
тот же результат.
Вернуться к: Функции обработки ошибок
PHP — это достаточно свободный язык программирования, и это, на мой взгляд, большой минус. Главным недостатком здесь является то, что некоторые конструкции, которые в других языках сразу же отключат выполнение программы, в PHP является нормой и вполне допустимыми. Но если Вы хотите писать код изначально грамотно, то Вам необходимо знать о том, как выводить ошибки разных уровней.
В PHP есть несколько уровней ошибок, которые представлены в таблице ниже:
| E_WARNING | Различного рода предупреждения. Например, если функция требует 3 параметра, а Вы передаёте только 2, то будет как раз ошибка уровня E_WARNING. |
| E_NOTICE | Примерно то же самое, что и E_WARNING, но ошибки это очень мелкие, и они лишь могут стать причиной ошибок в будущем. Пример: использование неинициализированной переменной. Могу сказать, что данный уровень ошибок встречается практически в каждом мало-мальски сложном скрипте. |
| E_DEPRECATED | Данный уровень ошибок возникает при использовании устаревших конструкций, например, при вызове какой-нибудь старой функции. |
| E_PARSE | Ошибка синтаксического характера. Например, забыли поставить круглую скобку. |
| E_ERROR | Ошибка, которая нам хорошо знакома. Как правило, мы её видем чаще всего. Самый простой пример — это вызов несуществующей функции. |
| E_ALL | Все ошибки. |
На большинстве серверов стоит вывод ошибок уровня E_WARNING, E_PARSE и E_ERROR. То есть очень грубые замечания и фатальные ошибки. Если Вы хотите программировать профессионально, то контроль только таких ошибок не достаточен.
Я рекомендую на этапе создания проекта включать вывод уровня ошибок E_ALL. Сделать это очень просто:
<?php
error_reporting(E_ALL);
?>
И так нужно писать перед началом каждого скрипта. Если данный способ сильно не удобен, и Вы имеете доступ к php.ini, то в этом файле найдите директиву error_reporting и поставьте у неё значение E_ALL.
Если Вы с выводом такого уровня ошибок в PHP напишите код без единого замечания, то, значит, Вы создали, как минимум, неплохой продукт. Когда будете выкладывать уже на хостинг, то рекомендую данный уровень ошибок стереть, чтобы они не появлялись время от времени. Ведь PHP тоже обновляется и сегодня новые конструкции завтра могут уже устареть. И чтобы не вызывать ошибку уровня E_DEPRECATED, рекомендую отключать отображение подобных ошибок.
-
Создано 03.10.2012 08:13:35
-

Михаил Русаков
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
-
Кнопка:
Она выглядит вот так:

-
Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт
- BB-код ссылки для форумов (например, можете поставить её в подписи):
PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:
E_ALL– все ошибки,E_ERROR– критические ошибки,E_WARNING– предупреждения,E_PARSE– ошибки синтаксиса,E_NOTICE– замечания,E_CORE_ERROR– ошибки обработчика,E_CORE_WARNING– предупреждения обработчика,E_COMPILE_ERROR– ошибки компилятора,E_COMPILE_WARNING– предупреждения компилятора,E_USER_ERROR– ошибки пользователей,E_USER_WARNING– предупреждения пользователей,E_USER_NOTICE– уведомления пользователей.
1
Вывод ошибок в браузере
error_reporting(E_ALL);
ini_set('display_errors', 'On');
PHP
В htaccess
php_value error_reporting "E_ALL"
php_flag display_errors On
htaccess
На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.
2
Запись ошибок в лог файл
error_reporting(E_ALL);
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');
PHP
Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:
Order Allow,Deny
Deny from all
htaccess
Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):
<FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
Order Allow,Deny
Deny from all
</FilesMatch>
htaccess
3
Отправка ошибок на e-mail
Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.
Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.
register_shutdown_function('error_alert');
function error_alert()
{
$error = error_get_last();
if (!empty($error)) {
mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true));
}
}
PHP
Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.
Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.
function error_alert($type, $message, $file, $line, $vars)
{
$error = array(
'type' => $type,
'message' => $message,
'file' => $file,
'line' => $line
);
error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
}
set_error_handler('error_alert');
PHP
4
Пользовательские ошибки
PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():
trigger_error('Пользовательская ошибка', E_USER_ERROR);
PHP
Результат:
Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
E_USER_ERROR– критическая ошибка,E_USER_WARNING– не критическая,E_USER_NOTICE– сообщения которые не являются ошибками,E_USER_DEPRECATED– сообщения о устаревшем коде.
10.10.2019, обновлено 09.10.2021
Другие публикации
Список основных кодов состояния HTTP, без WebDAV.
Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…
JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…
phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…
AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.
После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…
on
June 25, 2020
Errors are undesirable for users and you should do everything in your control to keep users away from them. However, they are of utmost importance for developers. They allow developers to understand the inaccuracies and vulnerabilities in their code by alerting them when their code breaks. They also provide relevant information about what went wrong, where, and what can be done to make amends. Absence of intelligent error reporting can not only make it extremely difficult to debug your project but can also let unnoticed, unresolved inconsistencies bleed into production code.
Most errors in PHP are by default not reported. This might be helpful for web applications in production, where you don’t want users to come across obscure error messages. However, during development, it is imperative to enable error messages — to be alerted about potential inaccuracies in your code before it is released for production.
In this post, we will look at what an error in PHP is, the different types of errors, and how you can enable error reporting in PHP.
Use these links to jump ahead in the tutorial:
What is a PHP error?
Common PHP Error Codes
Turn on Error Reporting in PHP
How to Log Errors in PHP
Conclusion
What is a PHP Error?
An error is an indication of something going wrong in your web application. It is usually encountered when a part of your code has not been properly implemented, for example — mistakes in the syntax, logical inconsistencies, inattention to handling invalid user input, etc. An error in programming paradigms can be as trivial as a missed semicolon or an unclosed parenthesis to something as big as an undefined class function or an unhandled invalid user input.
Let us look at a few common PHP error categories and codes.
Types of PHP Errors
There are primarily four types of errors in PHP —
- Fatal run-time errors
- Warning errors
- Parse errors (Syntax errors)
- Notice errors
Note: We are able to access error messages in the example outputs shown below because error reporting has been turned on for visualization. We will look at how one can enable error messages in the next section.
Fatal run-time errors (E_ERROR | Code 1)
As the name suggests, these errors can not be recovered from. They are encountered when the operation specified in your code can not be performed. As a result, execution is halted.
For example — if you try to call a function that has not been defined, a fatal run-time error would be raised.
<?php
function foo() {
echo "Function foo called.";
}
boo(); // undefined function 'boo'
?>
Warning errors (E_WARNING | Code 2)
A warning error is more subtle in that regard. It does not halt execution — just acts as a friendly reminder of something incorrect in your code, that might pose a bigger problem in the future.
The most common example of a warning error being raised is when you include a missing file in your code.
<?php
include('filename.txt'); // arbitrary file that is not present
echo "Hello world";
?>
Notice how the warning error has not forced the code to halt, allowing the print statement below to be executed.
Parse errors (E_PARSE | Code 4)
Parse errors are encountered as a result of purely syntactical mistakes in one’s code. These errors are generated during compilation, and as a result your code exits before it is run.
Parse error examples include — missing semicolons, unused or unclosed brackets, quotes, etc. Below is an example of the same.
<?php
echo "Hello world";
echo Hello world // no quotes or semicolon used
?>
Notice errors (E_NOTICE | Code 8)
Notice errors are similar to warning errors in that they are encountered during run-time and they don’t halt code execution. They indicate that something is incorrect in the script that even though doesn’t interrupt execution, should be fixed.
A common example would be trying to use an undefined variable in your code.
<?php
$a = 1;
$c = $a + $b; // undefined variable $b
echo "Hello world";
?>
Turn on Error Reporting in PHP
Error reporting in PHP is usually disabled by default. It can be enabled in three primary ways —
- Directly from code
- By editing the php.ini configuration file
- By editing the .htaccess file.
Before we look into the various methods, a word of caution is necessary. Make sure to disable error reporting for your web application’s production code. You wouldn’t want your users to come across obscure error messages when using your website.
Directly from code
Using the error_reporting() function
To configure error reporting in your PHP project, you can use the error_reporting function. This allows you to manipulate error reporting at run-time.
error_reporting ([ int $level ] ) : int
PHP has various types of errors that we looked at earlier in this post. These types can be provided to the error_reporting function as an argument to specify the kinds of errors that should be reported.
To report all PHP errors you can use the function in any of the two ways shown below.
<?php
// Report all PHP errors
error_reporting(E_ALL);
?>
or
<?php
// Report all PHP errors
error_reporting(-1);
?>
Both of the above-mentioned methods serve the same purpose, and therefore you can use either of them to enable error reporting for all types of errors.
Let us see this in action using an example —
<?php
error_reporting(E_ALL);
echo "Hello world";
// xyz is an undefined variable; should raise an error.
echo $xyz;
?>
OUTPUT:
As we can see, a Notice error has been reported. Had we not used the error_reporting function, PHP would have implicitly taken care of it and not reported anything at all.
This only strengthens our above argument about how unresolved issues can go unnoticed if errors are not appropriately reported.
You can also disable error reporting using the function as such —
//Turn off error reporting
error_reporting(0);
For reporting only specific kinds of errors, you can provide the required error types as a parameter to the error_reporting function using the bitwise OR operator as shown below —
// Report only selected kinds of errors
error_reporting(E_WARNING | E_ERROR | E_PARSE | E_NOTICE);
To enable error reporting for all but one (or more) error levels, you can use the below syntax —
// Report all errors except E_WARNING
error_reporting(E_ALL & ~E_WARNING);
Using the ini_set() function
We can also use the ini_set function to configure error reporting. This function allows us to initialize or modify the various configuration options (specified using a .ini file) directly from our code. This function modifies the configuration options only for the duration of the code (run-time).
You can call this function by adding the following line to your code —
ini_set('error_reporting', E_ALL);
We can similarly manipulate error reporting by applying different values for the ‘error_reporting’ option.
// Report selected kinds of errors
ini_set('error_reporting', E_WARNING | E_ERROR | E_PARSE | E_NOTICE);
Even though the ini_set function allows us to easily modify the configuration options directly from our code, it is a better practice to keep your PHP configurations in a separate php.ini file on your system. Let’s look at how we can do that in the next section.
By editing the php.ini configuration file
The php.ini serves as a configuration file for your project. It is read when PHP is initialized and can be used for a variety of things — storing environment variables, configuring server ports, error reporting, memory management, etc. You can find a list of the various configuration directives and their default values here.
Therefore, to enable error reporting in PHP, you need to edit this configuration file. The php.ini file is usually present in the /etc directory on Linux systems. You can locate the file by printing the output of the phpinfo() function in your code. The file’s path is provided under the ‘loaded configuration file’ row of the output.
Note: If the path mentioned in your output refers to a directory (for example- /etc) and not the file, you can create a new php.ini file inside that directory.
To enable error reporting, you can add either of the following lines to the php.ini file, and restart your server for the effects to take place.
error_reporting = E_ALL
or
error_reporting = -1
To also report errors encountered during PHP’s startup sequence, you can use the following directive in your php.ini file —
display_startup_errors = 1
Some posts on the internet also suggest enabling the ‘display_errors’ option for displaying error messages. In most cases, this is not required since that option is usually turned on by default in PHP.
If it is disabled in your system, you can turn it on by adding the following line in your php.ini file —
display_errors = 1
By editing the .htaccess file
The .htaccess (stands for hypertext-access) is a configuration file for manipulating various options provided by Apache-based web-servers.
Even though it can be a little difficult to set up initially based on your operating system, the .htaccess file allows you to exercise control over various server options at the local directory level and the global system level.
To enable error reporting, add the following two lines to your .htaccess file —
php_flag display_startup_errors on
php_flag display_errors on
Even though (as mentioned above) the display_errors property is by default ON, it is likely that your system admin might have disabled that property globally and you might want to enable it for a local project. Overriding the global property using the local .htaccess file can be a handy approach in such situations.
How to Log Errors in PHP
In large-scale PHP web applications that involve many processes like API requests, data processing etc, it is a good practice to store logs of your output and error messages. Good logging measures allow us to keep track of the inner workings of the system for effective debugging and maintenance. Let’s look at how we can create error logs in PHP.
You need to do two things to store error logs for your project —
- Enable ‘log_errors’ option
- Specify the ‘error_log’ file
Once this has been done, all your errors will be automatically logged to the specified error_log file. Just like error reporting, error logging can be set up from any of these three places — directly from code, from the php.ini configuration file and from the .htaccess file
Directly from code
Using the ini_set function we can configure the relevant PHP options as such —
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file
After doing this, all our errors would be automatically logged to the specified log file. Let us look at an example —
<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file
echo $b; // undefined variable should raise error
?>
Now, let’s open our project root folder and open the ‘my-error-file.log’ file to see if the error message has been logged.
As you can see, a timestamp has also been added to the error message, as we’d expect any effective logging system to do. All errors further encountered in your code will be appended to this file.
Another alternative to logging errors from your code would be to manually do so using the error_log function. You can use the function as shown below to write to a log file as shown below —
<?php
echo "Hello world";
// manually logging error message ->
error_log('My error message ⚠️', 3, 'my-error-file-2.log');
?>
The first and third arguments of the function represent the error message and the log file respectively. The second argument in the above function (3) is an option that specifies that the error message should be appended to the output of the file.
You can read more about the arguments of the error_log function here.
In this case, as can be seen, one has to specify the error message and the logging file each time. Also, in this method, timestamps are not added to the generated log messages by default.
Using the php.ini configuration file
Enabling logging from the configuration file is pretty straightforward. You only need to add two directives to your php.ini file as shown below —
log_errors = on
error_log = /path/my-error-file.log
After saving the file, restart your server to enable the automatic error logging to the specified file.
Using the .htaccess file
You can add the following two lines to your .htaccess file to enable error logging —
php_flag log_errors on
php_value error_log /path/my-error-file.log
This also serves the same purpose — enabling error logging, followed by specifying the output log file.
Conclusion
In this post, we learned about what PHP errors are, their different types (fatal errors, warnings, parse errors, and notices), about how important they are, and how you can enable error reporting for your web application. We looked at three different ways of initiating error reporting and storing log files — directly from code, through the php.ini configuration file, and from the server-based .htaccess file.
Now that you know how important it is to be mindful of errors, go ahead and enable error reporting in your project, maintain error logs, and build yourself a full-proof web application! You can also view your PHP errors in ScoutAPM’s dashboard. Also, make sure to disable error displaying when you release your website for production.
After you have enabled error reporting in your project, you might want to learn about how to handle these raised errors (exceptions) in your code. For this, you can refer to our post on Exception Handling in PHP — PHP Advanced Exceptions.
Stay safe! Keep learning! Happy coding!
