Пример записи ошибки

(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...

<?phpif($_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-разработчика, их возможная классификация, примеры их возникновения, влияние ошибок на ответ клиенту, а также инструкции по написанию своего обработчика ошибок.

Статья разбита на четыре раздела:

  1. Классификация ошибок.
  2. Пример, демонстрирующий различные виды ошибок и его поведение при различных настройках.
  3. Написание собственного обработчика ошибок.
  4. Полезные ссылки.

Классификация ошибок

Все ошибки, условно, можно разбить на категории по нескольким критериям.
Фатальность:

  • Фатальные
    Неустранимые ошибки. Работа скрипта прекращается.
    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.

Возможность перехвата ошибки функцией, определенной в set_error_handler():

  • Перехватываемые (не фатальные и смешанные)
    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.

Для нас, в рамках данной статьи, наиболее интересны классификации по первым двум критериям, о чем будет рассказано далее.

Примеры возникновения ошибок

Листинг index.php

<?php
// определеяем уровень протоколирования ошибок
error_reporting(E_ALL | E_STRICT);
// определяем режим вывода ошибок
ini_set('display_errors', 'On');
// подключаем файл с ошибками
require 'errors.php';

Листинг errors.php

<?php
echo "Файл с ошибками. Начало<br>";
/*
 * перехватываемые ошибки (ловятся функцией 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 {function f(){}} 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 {function f(int $a){}} $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 "Файл с ошибками. Конец<br>";

Примечание: для полной работоспособности скрипта необходим 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";, то ошибка попадет во вторую группу.

Значение, приведенной выше, таблицы можно описать следующим образом:

  1. Наличие в файле скрипта ошибки, приводящей его в «негодное» состояние (невозможность корректно обработать), на выходе даст пустое значение или же только само сообщение об ошибке, в зависимости от значения директивы display_errors.
  2. Скрипт в файле с фатальной ошибкой, не относящейся к первому пункту, будет выполняться в штатном режиме до самой ошибки.
  3. Наличие в файле фатальной ошибки при display_errors = Off обозначит 500 статус ответа.
  4. Не фатальные ошибки, как и следовало ожидать, в контексте возможности исполнения скрипта в целом, на работоспособность не повлияют.

Собственный обработчик ошибок

Для написания собственного обработчика ошибок необходимо знать, что:

  • для получения информации о последней произошедшей ошибке существует функция error_get_last();
  • для определения собственного обработчика ошибок существует функция set_error_handler(), но фатальные ошибки нельзя «перехватить» этой функцией;
  • используя register_shutdown_function(), можно зарегистрировать свою функцию, выполняемую по завершении работы скрипта, и в ней, используя знания из первого пункта, если фатальная ошибка имела место быть, предпринять необходимые действия;
  • сообщение о фатальной ошибке в любом случае попадет в буфер вывода;
  • воспользовавшись функциями контроля вывода можно предотвратить отображение нежелательной информации;
  • при использовании оператора управления ошибками (знак @) функция, определенная в set_error_handler() все равно будет вызвана, но функция error_reporting() в этом случае вернет 0, чем и можно пользоваться для прекращения работы или определения другого поведения своего обработчика ошибок.

Третий пункт поясню: зарегистрированная нами функция при помощи register_shutdown_function() выполнится в любом случае — корректно ли завершился скрипт, либо же был прерван в связи с критичной (фатальной) ошибкой. Второй вариант мы можем однозначно определить, воспользовавшись информацией предоставленной функцией error_get_last(), и, если ошибка все же была, выполнить наш собственный обработчик ошибок.
Продемонстрируем вышесказанное на модифицированном скрипте index.php:

<?php
/**
 * Обработчик ошибок
 * @param int $errno уровень ошибки
 * @param string $errstr сообщение об ошибке
 * @param string $errfile имя файла, в котором произошла ошибка
 * @param int $errline номер строки, в которой произошла ошибка
 * @return boolean
 */
function error_handler($errno, $errstr, $errfile, $errline)
{
    // если ошибка попадает в отчет (при использовании оператора "@" error_reporting() вернет 0)
    if (error_reporting() & $errno)
    {
        $errors = array(
            E_ERROR => '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 "<b>{$errors[$errno]}</b>[$errno] $errstr ($errfile на $errline строке)<br />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

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 — добавить эти строки в файл PHP:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Что именно делают эти строки?

Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.

Display_errors и display_startup_errors — это только две из доступных директив. Директива display_errors определяет, будут ли ошибки отображаться для пользователя. Обычно директива dispay_errors не должна использоваться для “боевого” режима работы сайта, а должна использоваться только для разработки.

display_startup_errors — это отдельная директива, потому что display_errors не обрабатывает ошибки, которые будут встречаться во время запуска PHP. Список директив, которые могут быть переопределены функцией ini_set, находится в официальной документации .

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

Отображение ошибок PHP через настройки в php.ini

Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:

display_errors = on

Директиву display_errors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию ini_set в коде PHP.

Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как “загруженный файл конфигурации” (“loaded configuration file”).

Отображать ошибки PHP через настройки в .htaccess

Включить или выключить отображение ошибок можно и с помощью файла .htaccess, расположенного в каталоге сайта.

php_flag display_startup_errors on
php_flag display_errors on

.htaccess также имеет директивы для display_startup_errors и display_errors.

Вы можете настроить display_errors в .htaccess или в вашем файле PHP.ini. Однако многие хостинг-провайдеры не разрешают вам изменять ваш файл PHP.ini для включения display_errors.

В файле .htaccess также можно включить настраиваемый журнал ошибок, если папка журнала или файл журнала доступны для записи. Файл журнала может быть относительным путем к месту расположения .htaccess или абсолютным путем, например /var/www/html/website/public/logs.

php_value error_log logs/all_errors.log

Включить подробные предупреждения и уведомления

Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:

error_reporting(E_WARNING);

Для отображения предупреждений и уведомлений укажите «E_WARNING | E_NOTICE».

Также можно указать E_ERROR, E_WARNING, E_PARSE и E_NOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «E_ALL & ~ E_NOTICE», где E_ALL обозначает все возможные параметры функции error_reporting.

Более подробно о функции error_reporting ()

Функция сообщения об ошибках — это встроенная функция PHP, которая позволяет разработчикам контролировать, какие ошибки будут отображаться. Помните, что в PHP ini есть директива error_reporting, которая будет задана ​​этой функцией во время выполнения.

error_reporting(0);

Для удаления всех ошибок, предупреждений, сообщений и уведомлений передайте в функцию error_reporting ноль. Можно сразу отключить сообщения отчетов в ini-файле PHP или в .htaccess:

error_reporting(E_NOTICE);

PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.

Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда E_NOTICE передается в функцию error_reporting, эти необъявленные переменные будут отображаться.

error_reporting(E_ALL & ~E_NOTICE);

Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «~» означает «нет», поэтому параметр ~ E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.

error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);

Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Error_reporting(E_ALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.

Включить ошибки php в файл с помощью функции error_log ()

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

Простой способ использовать файлы журналов — использовать функцию error_log, которая принимает четыре параметра. Единственный обязательный параметр — это первый параметр, который содержит подробную информацию об ошибке или о том, что нужно регистрировать. Тип, назначение и заголовок являются необязательными параметрами.

error_log("There is something wrong!", 0);

Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена ​​к любому файлу журнала, определенному на веб-сервере.

error_log("Email this error to someone!", 1, "someone@mydomain.com");

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

error_log("Write this error down to a file!", 3, "logs/my-errors.log");

Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.

Журнал ошибок PHP через конфигурацию веб-сервера

Лучший способ регистрировать ошибки — это определить их в файле конфигурации веб-сервера.

Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.

Пример для Apache:

ErrorLog "/var/log/apache2/my-website-error.log"

В nginx директива называется error_log.

error_log /var/log/nginx/my-website-error.log;

Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.

На чтение 11 мин Просмотров 1.2к. Опубликовано 16.10.2021

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

Содержание

  1. Что такое ошибка PHP?
  2. Какие бывают типы ошибок в PHP?
  3. Ошибки синтаксического анализа или синтаксиса
  4. Фатальные ошибки
  5. Предупреждение об ошибках
  6. Уведомление об ошибках
  7. Как включить отчеты об ошибках в PHP
  8. Сколько уровней ошибок доступно в PHP?
  9. Ошибки отображения PHP
  10. Что такое предупреждение PHP?
  11. Как помогают отчеты о сбоях
  12. Завершение отчета об ошибках 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 и добавить ее в свое приложение за считанные минуты.

How to Display PHP Errors and Enable Error Reporting

I still vividly remember the first time I learned about PHP error handling.

It was in my fourth year of programming, my second with PHP, and I’d applied for a developer position at a local agency. The application required me to send in a code sample (GitHub as we know it didn’t exist back then) so I zipped and sent a simple custom CMS I’d created the previous year.

The email I got back from the person reviewing the code still chills my bones to this day.

«I was a bit worried about your project, but once I turned error reporting off, I see it actually works pretty well».

That was the first time I searched «PHP error reporting», discovered how to enable it, and died inside when I saw the stream of errors that were hidden from me before.

PHP errors and error reporting are something that many developers new to the language might miss initially. This is because, on many PHP based web server installations, PHP errors may be suppressed by default. This means that no one sees or is even aware of these errors.

For this reason, it’s a good idea to know where and how to enable them, especially for your local development environment. This helps you pick up errors in your code early on.

If you Google «PHP errors» one of the first results you will see is a link to the error_reporting function documentation.

This function allows you to both set the level of PHP error reporting, when your PHP script (or collection of scripts) runs, or retrieve the current level of PHP error reporting, as defined by your PHP configuration.

The error_reporting function accepts a single parameter, an integer, which indicates which level of reporting to allow. Passing nothing as a parameter simply returns the current level set.

There is a long list of possible values you can pass as a parameter, but we’ll dive into those later.

For now it’s important to know that each possible value also exists as a PHP predefined constant. So for example, the constant E_ERROR has the value of 1. This means you could either pass 1, or E_ERROR to the error_reporting function, and get the same result.

As a quick example, if we create a php_error_test.php PHP script file, we can see the current error reporting level set, as well as set it to a new level.

<?php
// echo the current error reporting level
echo error_reporting();
<?php
// report all Fatal run-time errors.
echo error_reporting(1);

Error reporting configuration

Using the error_reporting function in this way is great when you just want to see any errors related to the piece of code you’re currently working on.

But it would be better to control which errors are being reported on in your local development environment, and log them somewhere logical, to be able to review as you code. This can be done inside the PHP initialization (or php.ini) file.

The php.ini file is responsible for configuring all the aspects of PHP’s behavior. In it you can set things like how much memory to allocate to PHP scripts, what size file uploads to allow, and what error_reporting level(s) you want for your environment.

If you’re not sure where your php.ini file is located, one way to find out is to create a PHP script which uses the phpinfo function. This function will output all the information relative to your PHP install.

<?php
phpinfo();

As you can see from my phpinfo, my current php.ini file is located at /etc/php/7.3/apache2/php.ini.

phpinfo

Once you’ve found your php.ini file, open it in your editor of choice, and search for the section called ‘Error handling and logging’. Here’s where the fun begins!

Error reporting directives

The first thing you’ll see in that section is a section of comments which include a detailed description of all the Error Level Constants. This is great, because you’ll be using them later on to set your error reporting levels.

Fortunately these constants are also documented in the online PHP Manual, for ease of reference.

Below this list is a second list of Common Values. This shows you how to set some commonly used sets of error reporting value combinations, including the default values, the suggested value for a development environment, and the suggested values for a production environment.

; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

Finally, at the bottom of all the comments is the current value of your error_reporting level. For local development, I’d suggest setting it to E_ALL, so as to see all errors.

error_reporting = E_ALL

This is usually one of the first things I set when I set up a new development environment. That way I’ll see any and all errors that are reported.

After the error_reporting directive, there are some additional directives you can set. As before, the php.ini file includes descriptions of each directive, but I’ll give a brief description of the important ones below.

The display_errors directive allows you to toggle whether PHP outputs the errors or not. I usually have this set to On, so I can see errors as they happen.

display_errors=On

The display_startup_errors allows for the same On/Off toggling of errors that may occur during PHP’s startup sequence. These are typically errors in your PHP or web server configuration, not specifically your code. It’s recommended to leave this Off, unless you’re debugging a problem and you aren’t sure what’s causing it.

The log_errors directive tells PHP whether or not to log errors to an error log file. This is always On by default, and is recommended.

The rest of the directives can be left as the default, except for maybe the error_log directive, which allows you to specify where to log the errors, if log_errors is on. By default it will log the errors wherever your web server has defined them to be logged.

Custom error logging

I use the Apache web server on Ubuntu, and my project-specific virtual host configurations use the following to determine the location for the error log.

ErrorLog ${APACHE_LOG_DIR}/project-error.log

This means it will log to the default Apache log directory, which is /var/log/apache2, under a file called project-error.log. Usually I replace project with the name of the web project it relates to.

So, depending on your local development environment you may need to tweak this to suit your needs. Alternatively, if you can’t change this at the web server level, you can set it at the php.ini level to a specific location.

error_log = /path/to/php.log

It is worth noting that this will log all PHP errors to this file, and if you’re working on multiple projects that might not be ideal. However, always knowing to check that one file for errors might work better for you, so your mileage may vary.

Find and fix those errors

If you’ve recently started coding in PHP, and you decide to turn error reporting on, be prepared to deal with the fallout from your existing code. You may see some things you didn’t expect, and need to fix.

The advantage though, is now that you know how to turn it all on at the server level, you can make sure you see these errors when they happen, and deal with them before someone else sees them!

Oh, and if you were wondering, the errors I was referring to at the start of this post were related to the fact that I was defining constants incorrectly, by not adding quotes around the constant name.

define(CONSTANT, 'Hello world.');

PHP allowed (and might still allow) this, but it would trigger a notice.

Notice: Use of undefined constant CONSTANT - assumed 'CONSTANT' 

This notice was triggered every time I defined a constant, which for that project was about 8 or 9 times. Not great for someone to see 8 or 9 notices at the top of each page…



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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 коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

next →
← prev

The error_reporting() is a pre-defined function of PHP. It allows you to control how many and which PHP errors will be reported. As we already discussed that PHP has several levels of errors. Using the error_reporting() function sets that level for the duration of your current script.

The php.ini file has an error_reporting directive that will be set at runtime by this function.

Syntax

The $level is an optional parameter in error_reporting() function. If the level is not set, this function will return the current error reporting level.

level (Optional)

This parameter specifies the error-report level for the current script.

Return Values

If the level parameter is not given, it will return the current level. Otherwise, it will revert to the old error_reporting level.

Changes

Versions Description
PHP 5.4 E_STRICT has become a part of E_ALL.
PHP 5.3 E_DEPRECATED and E_USER_DEPRECATED are newly added in PHP 5.3. 
PHP 5.2 E_RECOVERABLE_ERROR is added in PHP 5.2.
PHP 5.0 E_STRICT is newly introduced in PHP 5.0.

Example

With the help of PHP program specify different levels of error reporting:

Important Points of error_reporting()

  • By passing zero (0) in error_reporting function, you can remove all errors, warnings, notices, and parse messages. It would be much better to turn off report messages in .htaccess or in ini file instead of having this code in each or every PHP file.
  • PHP allows developers to use undeclared variables. But these undeclared variables can cause problems for the application when used in conditions and loop.
    Sometimes, this could happen that the variable which is declared and being used in conditions or loops have different spellings. So, to display the undeclared variable in the web application, pass the E_NOTICE in the error_reporting function.
  • The error_reporting() function allows the specific error to be displayed, which a user want. Using the ~ character, you can filter the error. For example — ~E_NOTICE means that notices will not be displayed. In the below line of code, all the errors will be displayed except E_NOTICE.
  • Below are the three lines of code given, which works same as the error_reporting(E_ALL) that means it will also display all PHP errors. The error_reporting(E_ALL) is most widely used to display errors because it is easy to read and understand.

Next TopicPHP header()

← prev
next →

error_reporting() in PHP

Introduction to error_reporting() in PHP

In the various levels of errors that PHP has, error_reporting is a function in PHP which indicates what are the errors reported and determines the error_reporting directive during runtime. Using this function we can set the prescribed level for the required duration (usually the runtime) of our script. It returns the old error reporting level based on the input given, or the present reporting level when no parameter is given.

Syntax with Parameters

Following is a syntax with parameters:

Syntax:

error_reporting(level)

Parameters:

There is only a single parameter level which is optional and whose input function takes. It specifies the error reporting level for the present script. Accepted values are constant name and value number.

Note: To ensure compatibility for PHP future versions, named constants are recommended.

There are a few predefined constants whose description is as below:

1. E_Error: These indicate fatal runtime errors that cannot be recovered from and the script execution will be halted.

2. E_Warning: These are non-fatal errors where the execution of the script will continue.

3. E_Parse: This shows compile-time parse errors which are to be generated only by the parsers.

4. E_Notice: This issues runtime notices indicating that the script has found something which shows an error, but which can also happen while running a normal script.

5. E_Core_Error: During PHP’s initial startup there may arise a few fatal errors which are generated by PHP’s core.

6. E_Core_Warning: This shows the non-fatal errors which arise during PHP’s initial startup also generated by PHP’s core.

7. E_Compile_Error: These display fatal errors which occur during compile time. These are generated by the Zend scripting engine.

8. E_Compile_Warning: Similar to above these display compile-time warnings or can be called non-fatal errors and are also generated by Zend scripting engine.

9. E_User_Error: This displays errors generated by the users. This is similar to E_ERROR except that it is generated using PHP function in the PHP code.

10. E_All: This is like a combination of all the above which supports all errors and warnings except that of E_STRICT.

Return Values:

The error_reporting function gives the old reporting level or the present error reporting level if in case no parameters are given.

Working of error_reporting in PHP

This function allows the developer to actually control the different kinds of errors and how many of such errors will be thrown in the application. This function sets an error_reporting directive that will be present in the PHP ini configuration file.

error_reporting(0);
  • When 0 is passed to the error reporting function it removes all warnings, errors, parse related messages and notices, if any. Instead of having to include this line in each of the PHP code files, it is practical to have it added and to turn off these report messages in the ini file present or in the .htaccess.
error_reporting(E_NOTICE);
  • In PHP the variables can be used even when not declared. But this practice is not feasible as the undeclared variables may cause application related issues if it is used in conditional statements and loops. This may also take place because of the spelling mismatch between the declared variables and of that being used for conditions and loops. When this E_NOTICE will be passed into the error_reporting function, only then these undeclared variables will be shown in the web application.
error_reporting(E_ALL & ~E_NOTICE);
  • This error reporting function helps to filter out the errors which can be displayed. The “~” character here means the “not/no” and hence ~E_NOTICE here means to not show any notices. Here the “&” character represents “true for all” whereas “|” means as long as one of the parameters is true. They are exactly similar to the functions AND and OR in PHP.
error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);
  • All of the above lines serve the same purpose i.e. show all the errors. E_ALL is the most widely used function among all others by developers to display error messages as it is more comprehensible and intelligible.

Error Logging in PHP using error_log() Function

It happens so that during the production phase, error messages are to be hidden from the end-users but this information is needed to be registered for tracing purpose. And the best way to record these errors on the production web application is to write and store in log files.

An easy way to log these is by using the error_log function which takes our parameters as input. The only mandatory parameter here is the first one which contains details about the errors and what all to be logged. Other parameters like the type, destination, and header are non-mandatory here for this function.

error_log("Error found!", 0);
  • The type parameter will be set to 0 by default if not given, and the log information will be appended at the end of the log file generated in the webserver.
error_log("Error information being emailed!", 1, "id@mydomain.com");
  • The type parameter here is 1 will email this log specified in the 3rd parameter which is the email id. For this to work, the PHP ini file must be having a correct SMTP configuration to send out emails. Some of the parameters required for these include host, encryption type, port, password and username.
error_log("Write errors to this file", 3, "https://cdn.educba.com/tmp/errorfile.log");
  • The same error logs can also be written down to the required file whose path will be given in the third parameter. Make sure the given path has all required permissions.

Example of error_reporting() in PHP

Given below is the example:

Code:

<?php
$a = 1;
trigger_error("user warning!", E_USER_WARNING);
$a = 2;
echo "Value of $a is ${$a}";
error_reporting(0);
error_reporting(E_ALL);
?>

Output:

error_reporting in php 1

Advantages of using error_reporting function in PHP

  • error_reporting is good for debugging purposes and for developing web application.
  • Each and every error can be logged and fixed as soon as it happens using this function.
  • To not show it to the end-user, make sure you redirect the errors to a log file while releasing it.

Conclusion

Hence we can say that error_reporting() function in PHP are therefore helpful in cases when there are a lot of problems with the PHP web application and we need to display all of these errors and warnings either for development or debugging purposes. It is a function we can enable different kinds of warnings or error messages and most of them are as discussed above.

Recommended Articles

This is a guide to error_reporting() in PHP. Here we discuss the introduction, working of error_reporting in PHP, error logging in PHP using error_log() function and advantages. You may also have a look at the following articles to learn more –

  1.  PHP Tag in HTML
  2. Validation in PHP
  3. PHP Data Object
  4. PHP Interface

Автор: Ольга Рябова

Целью составления отчёта об ошибке является её исправление. О том как описать ошибку, из чего состоит описание ошибки и как оно может выглядеть на примере расскажет этот материал.

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

Первым делом желательно успокоиться и не делать резких движений, не нажимать лишних кнопок и т.д. Надо вспомнить последовательность действий, которые были произведены и попытаться воспроизвести ситуацию. Лучше это делать в новом окне браузера (если речь идёт о web-приложении). Ну и записывать вводимые данные/команды, какие кнопки нажимались, в какие меню производился переход, какая реакция системы на эти действия, какое сообщение об ошибке выводится.

Теперь надо записать свои действия. Записывать надо коротко, но ясно и понятно. Найти золотую середину. Если написать мемуары, то программист их не будет читать или подумает, что ошибка очень трудная и отложит на потом, а сверхкороткий отчёт никто не поймёт. Как следствие исправление ошибки (бага) повиснет в воздухе или отправят обратно вам с пометкой «не воспроизводится» или попросят уточнений, тем самым потратив попросту и Ваше и своё время. Также не стоит в один отчёт вписывать более одной ошибки. Мотив всё тот же.

Отчёт пишется не только для себя, но и для других. Так что, его надо писать так, чтобы поняли все, а не догадывались что Вы хотели сказать, не переспрашивали. Задайте себе вопрос: а сможет ли повторить Ваши действия человек, который первый раз видит продукт?

Если возможно, попробуйте разные варианты чтобы выразить точно проблему.

Желательно также избегать жаргона или выражений которые могут быть трудны для понимания другими.

Ни в коем случае не надо передавать в устной форме отчёты об ошибках, писать по электронной почте, по icq и т.д.! В большинстве случаев о них забывают, не относятся к ним серьёзно и если их не исправят, то в первую очередь в этом будете виноваты Вы. Вам это надо? Все ошибки должны быть учтены и описаны и иметь свой индивидуальный номер. Тогда при неисправлении ошибки вся ответственность будет на программисте.

Эти записи об ошибках понадобятся другим тестировщикам работающим с Вами, менеджерам для того, чтобы они видели что Вы работаете и работаете продуктивно, тестировщикам, которые придут вместо Вас, а так же для написания отчётов.

Описание ошибки

Теперь перейдём к описанию ошибки. В зависимости от того какая в компании багтрекинговая система (система учёта ошибок), будут и разные поля для ввода.

В начале открываем новый отчёт об ошибке. Вполне возможно, что Вы увидите много граф для заполнения, но возможно, что их не все надо заполнять. Лучше проконсультируйтесь с другими тестировщиками, менеджером или руководителем группы тестирования. Но скорее всего придётся заполнить следующие поля:

Приоритет (насколько серьёзная ошибка и какой скорости выполнения требует. Быстро надо исправить или можно подождать)

Назначить (кто будет заниматься ошибкой)

Класс (это какой вид ошибки- серьёзная, незначительная, опечатка…)

Заголовок ошибки

Заголовок должен кратко и полностью описывать проблему. Мы тратим много времени пролистывая базу ошибок и просматривая заголовки ошибок. Много времени можно сэкономить если заголовки будут понятны и не придётся открывать описание ошибки, чтобы понять что имелось в виду.

Описание проблемы

Описывать проблему лучше с помощью «стрелочек». С помощью них из текста отчёта выкидывается много ненужных слов, которые мешают понимать суть дела.

Пример: Открыл www.aaa.ru —> ввел в поле bbb слово ccc —>нажал кнопку ddd —> система выдала ошибку: ddd

Пример из жизни

Заголовок: Проблема с меню «забыли пароль»

Описание проблемы: Зайти на страницу авторизации —> нажать кнопку «Забыли пароль?» —> в поле «Лицевой счёт» вписать 2389 —> в поле «e-mail» вписать
Этот e-mail адрес защищен от спам-ботов, для его просмотра у Вас должен быть включен Javascript
—> система пишет: «Ошибка отправки сообщения. (#1)»

При необходимости данные операционной среды, конфигурации, логи. Есть ли зависимость от конфигурации, условия инсталляции, параметры, настройки, версия и т.д.

Приложения (Attachments)

Чтобы отчёт сделать более подробным и наглядным можно и нужно прибегнуть к использованию:

  • ссылок
  • скриншотов
  • видео записи

Ссылка

Ну тут всё понятно. Выскочила ошибка — берётся ссылка на эту страницу и вставляется отчёт. Желательно ещё и со скриншотом. (при условии, что тестируется веб-приложение — прим. редактора)

Скриншоты

Очень полезная вещь для визуализации проблемы. Делаете скриншот проблемной зоны. (Самое простое — это на клавиатуре найти кнопку Print Screen, нажать её потом в открыть программку Paint (если мы находимся в операционной системе семейства Windows — прим. редактора), которая автоматически устанавливается в Windows и в ней нажать Ctrl-V, потом вырезать ненужное, сохранить (лучше в формате JPG))

Хотя, есть и более профессиональные программки, которые более приспособлены к такого рода действиям и имеют много очень полезных функций, например SnagIt, HyperSnap, HardCopy, RoboScreenCapture, FullShot 9, HyperSnap-DX 5, TNT 2. Скриншот нужно прикрепить к отчёту об ошибке.

Видео ролики

Если ошибку тяжело описать, то это самый подходящий метод. Программы: SnagIt, CamStudio

(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

17 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.

ecervetti at orupaca dot fr

14 years ago


It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135

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

5 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/

luisdev

5 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.

qeremy ! gmail

8 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);
}
?>

adam at adamhahn dot com

6 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
);
?>

keithm at aoeex dot com

13 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.

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).

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.

vdephily at bluemetrix dot com

18 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
?>

&IT

3 years ago


error_reporting(E_ALL);
if (!ini_get('display_errors')) {
    ini_set('display_errors', '1');
}

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 …

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]

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);?>

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?

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.

teynon1 at gmail dot com

11 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);
?>

Daz Williams (The Northeast)

14 years ago


Only display php errors to the developer...

<?phpif($_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.

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

...

misplacedme at gmail dot com

14 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.
?>

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();
  }

Время на прочтение
6 мин

Количество просмотров 66K

В статье представлена очередная попытка разобраться с ошибками, которые могут встретиться на вашем пути php-разработчика, их возможная классификация, примеры их возникновения, влияние ошибок на ответ клиенту, а также инструкции по написанию своего обработчика ошибок.

Статья разбита на четыре раздела:

  1. Классификация ошибок.
  2. Пример, демонстрирующий различные виды ошибок и его поведение при различных настройках.
  3. Написание собственного обработчика ошибок.
  4. Полезные ссылки.

Классификация ошибок

Все ошибки, условно, можно разбить на категории по нескольким критериям.
Фатальность:

  • Фатальные
    Неустранимые ошибки. Работа скрипта прекращается.
    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.

Возможность перехвата ошибки функцией, определенной в set_error_handler():

  • Перехватываемые (не фатальные и смешанные)
    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.

Для нас, в рамках данной статьи, наиболее интересны классификации по первым двум критериям, о чем будет рассказано далее.

Примеры возникновения ошибок

Листинг index.php

<?php
// определеяем уровень протоколирования ошибок
error_reporting(E_ALL | E_STRICT);
// определяем режим вывода ошибок
ini_set('display_errors', 'On');
// подключаем файл с ошибками
require 'errors.php';

Листинг errors.php

<?php
echo "Файл с ошибками. Начало<br>";
/*
 * перехватываемые ошибки (ловятся функцией 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 {function f(){}} 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 {function f(int $a){}} $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 "Файл с ошибками. Конец<br>";

Примечание: для полной работоспособности скрипта необходим 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";, то ошибка попадет во вторую группу.

Значение, приведенной выше, таблицы можно описать следующим образом:

  1. Наличие в файле скрипта ошибки, приводящей его в «негодное» состояние (невозможность корректно обработать), на выходе даст пустое значение или же только само сообщение об ошибке, в зависимости от значения директивы display_errors.
  2. Скрипт в файле с фатальной ошибкой, не относящейся к первому пункту, будет выполняться в штатном режиме до самой ошибки.
  3. Наличие в файле фатальной ошибки при display_errors = Off обозначит 500 статус ответа.
  4. Не фатальные ошибки, как и следовало ожидать, в контексте возможности исполнения скрипта в целом, на работоспособность не повлияют.

Собственный обработчик ошибок

Для написания собственного обработчика ошибок необходимо знать, что:

  • для получения информации о последней произошедшей ошибке существует функция error_get_last();
  • для определения собственного обработчика ошибок существует функция set_error_handler(), но фатальные ошибки нельзя «перехватить» этой функцией;
  • используя register_shutdown_function(), можно зарегистрировать свою функцию, выполняемую по завершении работы скрипта, и в ней, используя знания из первого пункта, если фатальная ошибка имела место быть, предпринять необходимые действия;
  • сообщение о фатальной ошибке в любом случае попадет в буфер вывода;
  • воспользовавшись функциями контроля вывода можно предотвратить отображение нежелательной информации;
  • при использовании оператора управления ошибками (знак @) функция, определенная в set_error_handler() все равно будет вызвана, но функция error_reporting() в этом случае вернет 0, чем и можно пользоваться для прекращения работы или определения другого поведения своего обработчика ошибок.

Третий пункт поясню: зарегистрированная нами функция при помощи register_shutdown_function() выполнится в любом случае — корректно ли завершился скрипт, либо же был прерван в связи с критичной (фатальной) ошибкой. Второй вариант мы можем однозначно определить, воспользовавшись информацией предоставленной функцией error_get_last(), и, если ошибка все же была, выполнить наш собственный обработчик ошибок.
Продемонстрируем вышесказанное на модифицированном скрипте index.php:

<?php
/**
 * Обработчик ошибок
 * @param int $errno уровень ошибки
 * @param string $errstr сообщение об ошибке
 * @param string $errfile имя файла, в котором произошла ошибка
 * @param int $errline номер строки, в которой произошла ошибка
 * @return boolean
 */
function error_handler($errno, $errstr, $errfile, $errline)
{
    // если ошибка попадает в отчет (при использовании оператора "@" error_reporting() вернет 0)
    if (error_reporting() & $errno)
    {
        $errors = array(
            E_ERROR => '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 "<b>{$errors[$errno]}</b>[$errno] $errstr ($errfile на $errline строке)<br />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

Today, we’ll see how you can use the error_reporting function in PHP for debugging purposes.

The error_reporting function allows you to configure which errors will be reported in your PHP scripts. In fact, when you use the error_reporting function in your PHP script, it just sets the error_reporting directive at runtime. If you’re aware of the php.ini configuration file, it provides a lot of configuration directives for different purposes, and the error_reporting directive is one of them. Specifically, the error_reporting directive allows you to set the error reporting level in your PHP scripts.

In this quick article, we’ll go through the basics of the error_reporting function, and we’ll discuss how you can use it effectively in your day-to-day PHP development.

Syntax

Let’s quickly go through the syntax of the error_reporting function.

1
error_reporting(int $error_level = null): int

It takes a single argument which allows you to pass the error level which you want to set. It’s an optional argument, so if you don’t pass it, it should return the current error reporting level.

You could pass either a bit-mask or named constants in this argument. However, it’s recommended to pass named constants for the compatibility for future PHP versions. Also, if you use named constants, it increases readability of your code as well.

There are different error constants that you could pass in the first argument of the error_reporting function. Following is the quick list of all constants.

  • E_ERROR: display fatal run-time errors
  • E_WARNING: display run-time warnings
  • E_PARSE: display compile-time parse errors
  • E_NOTICE: display run-time notices
  • E_CORE_ERROR: display fatal errors that occur during PHP’s initial startup
  • E_CORE_WARNING: display warnings that occur during PHP’s initial startup
  • E_COMPILE_ERROR: display fatal compile-time errors
  • E_COMPILE_WARNING: display fatal compile-time warnings
  • E_USER_ERROR: display the user-generated error message
  • E_USER_WARNING: display the user-generated warning message
  • E_USER_NOTICE: display the user-generated notice message
  • E_STRICT: suggest changes to your code which will ensure the best interoperability and forward compatibility
  • E_RECOVERABLE_ERROR: display catchable fatal errors
  • E_DEPRECATED: display warnings about code that will not work in future versions
  • E_USER_DEPRECATED: similar to E_DEPRECATED, but it display only user-generated warning messages
  • E_ALL: display all errors, warnings, and notices

Each constant allows you to set a different level of error reporting. In the next section, we’ll see how you can use the error_reporting function in your day-to-day PHP development.

How to Use the error_reporting Function

In the previous section, we went through the syntax of the error_reporting function. In this section, we’ll see how you can use it in your PHP scripts.

Display All Errors

Let’s quickly go through the following example.

1
<?php
2
error_reporting(E_ALL);
3
ini_set('display_errors', 1);
4
echo $foo;
5
?>

In the above example, we’ve passed the E_ALL constant in the first argument of the error_reporting function, and thus, it will display all errors, warnings and notices in our script. If you run the above script, it should display the following error.

1
Notice: Undefined variable: foo in /web/demo/error_reporting.php on line 4

Since, we are using the $foo variable without defining it beforehand, it throws a notice to inform you that you should define the $foo variable before you actually use it.

Alternatively, you could also pass -1 instead of the E_ALL constant as shown in the following snippet, and it would show every possible error.

1
<?php
2
error_reporting(-1);
3
?>

The E_ALL constant is really useful to debug the famous WSOD (white screen of death) error.

Display All Errors Except Notices

Let’s go through the following example.

1
<?php
2
error_reporting(E_ALL & ~E_NOTICE);
3
ini_set('display_errors', 1);
4
echo $foo;
5
?>

When you use the error_reporting function, you can use operators like &, | and ~ to omit and filter specific types of errors. In the above example, we want to display all types of errors but notices, and thus, we’ve used the ~ operator in front of the E_NOTICE constant. If you run the above script, it won’t display the notice which it would have displayed, had you used only the E_ALL constant.

Display Notices and Warnings

In this section, we’ll see how you can display only specific types of errors. Let’s quickly go through the following example.

1
<?php
2
error_reporting(E_WARNING | E_NOTICE);
3
ini_set('display_errors', 1);
4
include "foo_bar.php";
5
echo $foo;
6
?>

In the above example, we are instructing the error_reporting function that we want to display only warnings and notices. As you can see, we’ve used the | operator, so it would display both types of errors.

So that’s how you can use the error_reporting function with different types of error constants for debugging purposes in your day-to-day PHP development.

Conclusion

Today, we discussed how you can use the error_reporting function in PHP to debug errors in your PHP scripts. We discussed how you can use it to display different levels of errors during development.

Did you find this post useful?

Sajal Soni

Software Engineer, FSPL, India

I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.

Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.

I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

(PHP 4, PHP 5, PHP 7, PHP

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...

<?phpif($_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-разработчика, их возможная классификация, примеры их возникновения, влияние ошибок на ответ клиенту, а также инструкции по написанию своего обработчика ошибок.

Статья разбита на четыре раздела:

  1. Классификация ошибок.
  2. Пример, демонстрирующий различные виды ошибок и его поведение при различных настройках.
  3. Написание собственного обработчика ошибок.
  4. Полезные ссылки.

Классификация ошибок

Все ошибки, условно, можно разбить на категории по нескольким критериям.
Фатальность:

  • Фатальные
    Неустранимые ошибки. Работа скрипта прекращается.
    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.

Возможность перехвата ошибки функцией, определенной в set_error_handler():

  • Перехватываемые (не фатальные и смешанные)
    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.

Для нас, в рамках данной статьи, наиболее интересны классификации по первым двум критериям, о чем будет рассказано далее.

Примеры возникновения ошибок

Листинг index.php

<?php
// определеяем уровень протоколирования ошибок
error_reporting(E_ALL | E_STRICT);
// определяем режим вывода ошибок
ini_set('display_errors', 'On');
// подключаем файл с ошибками
require 'errors.php';

Листинг errors.php

<?php
echo "Файл с ошибками. Начало<br>";
/*
 * перехватываемые ошибки (ловятся функцией 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 {function f(){}} 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 {function f(int $a){}} $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 "Файл с ошибками. Конец<br>";

Примечание: для полной работоспособности скрипта необходим 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";, то ошибка попадет во вторую группу.

Значение, приведенной выше, таблицы можно описать следующим образом:

  1. Наличие в файле скрипта ошибки, приводящей его в «негодное» состояние (невозможность корректно обработать), на выходе даст пустое значение или же только само сообщение об ошибке, в зависимости от значения директивы display_errors.
  2. Скрипт в файле с фатальной ошибкой, не относящейся к первому пункту, будет выполняться в штатном режиме до самой ошибки.
  3. Наличие в файле фатальной ошибки при display_errors = Off обозначит 500 статус ответа.
  4. Не фатальные ошибки, как и следовало ожидать, в контексте возможности исполнения скрипта в целом, на работоспособность не повлияют.

Собственный обработчик ошибок

Для написания собственного обработчика ошибок необходимо знать, что:

  • для получения информации о последней произошедшей ошибке существует функция error_get_last();
  • для определения собственного обработчика ошибок существует функция set_error_handler(), но фатальные ошибки нельзя «перехватить» этой функцией;
  • используя register_shutdown_function(), можно зарегистрировать свою функцию, выполняемую по завершении работы скрипта, и в ней, используя знания из первого пункта, если фатальная ошибка имела место быть, предпринять необходимые действия;
  • сообщение о фатальной ошибке в любом случае попадет в буфер вывода;
  • воспользовавшись функциями контроля вывода можно предотвратить отображение нежелательной информации;
  • при использовании оператора управления ошибками (знак @) функция, определенная в set_error_handler() все равно будет вызвана, но функция error_reporting() в этом случае вернет 0, чем и можно пользоваться для прекращения работы или определения другого поведения своего обработчика ошибок.

Третий пункт поясню: зарегистрированная нами функция при помощи register_shutdown_function() выполнится в любом случае — корректно ли завершился скрипт, либо же был прерван в связи с критичной (фатальной) ошибкой. Второй вариант мы можем однозначно определить, воспользовавшись информацией предоставленной функцией error_get_last(), и, если ошибка все же была, выполнить наш собственный обработчик ошибок.
Продемонстрируем вышесказанное на модифицированном скрипте index.php:

<?php
/**
 * Обработчик ошибок
 * @param int $errno уровень ошибки
 * @param string $errstr сообщение об ошибке
 * @param string $errfile имя файла, в котором произошла ошибка
 * @param int $errline номер строки, в которой произошла ошибка
 * @return boolean
 */
function error_handler($errno, $errstr, $errfile, $errline)
{
    // если ошибка попадает в отчет (при использовании оператора "@" error_reporting() вернет 0)
    if (error_reporting() & $errno)
    {
        $errors = array(
            E_ERROR => '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 "<b>{$errors[$errno]}</b>[$errno] $errstr ($errfile на $errline строке)<br />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

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 — добавить эти строки в файл PHP:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Что именно делают эти строки?

Функция ini_set попытается переопределить конфигурацию, найденную в вашем ini-файле PHP.

Display_errors и display_startup_errors — это только две из доступных директив. Директива display_errors определяет, будут ли ошибки отображаться для пользователя. Обычно директива dispay_errors не должна использоваться для “боевого” режима работы сайта, а должна использоваться только для разработки.

display_startup_errors — это отдельная директива, потому что display_errors не обрабатывает ошибки, которые будут встречаться во время запуска PHP. Список директив, которые могут быть переопределены функцией ini_set, находится в официальной документации .

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

Отображение ошибок PHP через настройки в php.ini

Если ошибки в браузере по-прежнему не отображаются, то добавьте директиву:

display_errors = on

Директиву display_errors следует добавить в ini-файл PHP. Она отобразит все ошибки, включая синтаксические ошибки, которые невозможно отобразить, просто вызвав функцию ini_set в коде PHP.

Актуальный INI-файл можно найти в выводе функции phpinfo (). Он помечен как “загруженный файл конфигурации” (“loaded configuration file”).

Отображать ошибки PHP через настройки в .htaccess

Включить или выключить отображение ошибок можно и с помощью файла .htaccess, расположенного в каталоге сайта.

php_flag display_startup_errors on
php_flag display_errors on

.htaccess также имеет директивы для display_startup_errors и display_errors.

Вы можете настроить display_errors в .htaccess или в вашем файле PHP.ini. Однако многие хостинг-провайдеры не разрешают вам изменять ваш файл PHP.ini для включения display_errors.

В файле .htaccess также можно включить настраиваемый журнал ошибок, если папка журнала или файл журнала доступны для записи. Файл журнала может быть относительным путем к месту расположения .htaccess или абсолютным путем, например /var/www/html/website/public/logs.

php_value error_log logs/all_errors.log

Включить подробные предупреждения и уведомления

Иногда предупреждения приводят к некоторым фатальным ошибкам в определенных условиях. Скрыть ошибки, но отображать только предупреждающие (warning) сообщения можно вот так:

error_reporting(E_WARNING);

Для отображения предупреждений и уведомлений укажите «E_WARNING | E_NOTICE».

Также можно указать E_ERROR, E_WARNING, E_PARSE и E_NOTICE в качестве аргументов. Чтобы сообщить обо всех ошибках, кроме уведомлений, укажите «E_ALL & ~ E_NOTICE», где E_ALL обозначает все возможные параметры функции error_reporting.

Более подробно о функции error_reporting ()

Функция сообщения об ошибках — это встроенная функция PHP, которая позволяет разработчикам контролировать, какие ошибки будут отображаться. Помните, что в PHP ini есть директива error_reporting, которая будет задана ​​этой функцией во время выполнения.

error_reporting(0);

Для удаления всех ошибок, предупреждений, сообщений и уведомлений передайте в функцию error_reporting ноль. Можно сразу отключить сообщения отчетов в ini-файле PHP или в .htaccess:

error_reporting(E_NOTICE);

PHP позволяет использовать переменные, даже если они не объявлены. Это не стандартная практика, поскольку необъявленные переменные будут вызывать проблемы для приложения, если они используются в циклах и условиях.

Иногда это также происходит потому, что объявленная переменная имеет другое написание, чем переменная, используемая для условий или циклов. Когда E_NOTICE передается в функцию error_reporting, эти необъявленные переменные будут отображаться.

error_reporting(E_ALL & ~E_NOTICE);

Функция сообщения об ошибках позволяет вам фильтровать, какие ошибки могут отображаться. Символ «~» означает «нет», поэтому параметр ~ E_NOTICE означает не показывать уведомления. Обратите внимание на символы «&» и «|» между возможными параметрами. Символ «&» означает «верно для всех», в то время как символ «|» представляет любой из них, если он истинен. Эти два символа имеют одинаковое значение в условиях PHP OR и AND.

error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);

Эти три строки кода делают одно и то же, они будут отображать все ошибки PHP. Error_reporting(E_ALL) наиболее широко используется разработчиками для отображения ошибок, потому что он более читабелен и понятен.

Включить ошибки php в файл с помощью функции error_log ()

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

Простой способ использовать файлы журналов — использовать функцию error_log, которая принимает четыре параметра. Единственный обязательный параметр — это первый параметр, который содержит подробную информацию об ошибке или о том, что нужно регистрировать. Тип, назначение и заголовок являются необязательными параметрами.

error_log("There is something wrong!", 0);

Параметр type, если он не определен, будет по умолчанию равен 0, что означает, что эта информация журнала будет добавлена ​​к любому файлу журнала, определенному на веб-сервере.

error_log("Email this error to someone!", 1, "someone@mydomain.com");

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

error_log("Write this error down to a file!", 3, "logs/my-errors.log");

Для записи сообщений в отдельный файл необходимо использовать тип 3. Третий параметр будет служить местоположением файла журнала и должен быть доступен для записи веб-сервером. Расположение файла журнала может быть относительным путем к тому, где этот код вызывается, или абсолютным путем.

Журнал ошибок PHP через конфигурацию веб-сервера

Лучший способ регистрировать ошибки — это определить их в файле конфигурации веб-сервера.

Однако в этом случае вам нужно попросить администратора сервера добавить следующие строки в конфигурацию.

Пример для Apache:

ErrorLog "/var/log/apache2/my-website-error.log"

В nginx директива называется error_log.

error_log /var/log/nginx/my-website-error.log;

Теперь вы знаете, как в PHP включить отображение ошибок. Надеемся, что эта информация была вам полезна.

На чтение 11 мин Просмотров 1.2к. Опубликовано 16.10.2021

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

Содержание

  1. Что такое ошибка PHP?
  2. Какие бывают типы ошибок в PHP?
  3. Ошибки синтаксического анализа или синтаксиса
  4. Фатальные ошибки
  5. Предупреждение об ошибках
  6. Уведомление об ошибках
  7. Как включить отчеты об ошибках в PHP
  8. Сколько уровней ошибок доступно в PHP?
  9. Ошибки отображения PHP
  10. Что такое предупреждение PHP?
  11. Как помогают отчеты о сбоях
  12. Завершение отчета об ошибках 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 и добавить ее в свое приложение за считанные минуты.

How to Display PHP Errors and Enable Error Reporting

I still vividly remember the first time I learned about PHP error handling.

It was in my fourth year of programming, my second with PHP, and I’d applied for a developer position at a local agency. The application required me to send in a code sample (GitHub as we know it didn’t exist back then) so I zipped and sent a simple custom CMS I’d created the previous year.

The email I got back from the person reviewing the code still chills my bones to this day.

«I was a bit worried about your project, but once I turned error reporting off, I see it actually works pretty well».

That was the first time I searched «PHP error reporting», discovered how to enable it, and died inside when I saw the stream of errors that were hidden from me before.

PHP errors and error reporting are something that many developers new to the language might miss initially. This is because, on many PHP based web server installations, PHP errors may be suppressed by default. This means that no one sees or is even aware of these errors.

For this reason, it’s a good idea to know where and how to enable them, especially for your local development environment. This helps you pick up errors in your code early on.

If you Google «PHP errors» one of the first results you will see is a link to the error_reporting function documentation.

This function allows you to both set the level of PHP error reporting, when your PHP script (or collection of scripts) runs, or retrieve the current level of PHP error reporting, as defined by your PHP configuration.

The error_reporting function accepts a single parameter, an integer, which indicates which level of reporting to allow. Passing nothing as a parameter simply returns the current level set.

There is a long list of possible values you can pass as a parameter, but we’ll dive into those later.

For now it’s important to know that each possible value also exists as a PHP predefined constant. So for example, the constant E_ERROR has the value of 1. This means you could either pass 1, or E_ERROR to the error_reporting function, and get the same result.

As a quick example, if we create a php_error_test.php PHP script file, we can see the current error reporting level set, as well as set it to a new level.

<?php
// echo the current error reporting level
echo error_reporting();
<?php
// report all Fatal run-time errors.
echo error_reporting(1);

Error reporting configuration

Using the error_reporting function in this way is great when you just want to see any errors related to the piece of code you’re currently working on.

But it would be better to control which errors are being reported on in your local development environment, and log them somewhere logical, to be able to review as you code. This can be done inside the PHP initialization (or php.ini) file.

The php.ini file is responsible for configuring all the aspects of PHP’s behavior. In it you can set things like how much memory to allocate to PHP scripts, what size file uploads to allow, and what error_reporting level(s) you want for your environment.

If you’re not sure where your php.ini file is located, one way to find out is to create a PHP script which uses the phpinfo function. This function will output all the information relative to your PHP install.

<?php
phpinfo();

As you can see from my phpinfo, my current php.ini file is located at /etc/php/7.3/apache2/php.ini.

phpinfo

Once you’ve found your php.ini file, open it in your editor of choice, and search for the section called ‘Error handling and logging’. Here’s where the fun begins!

Error reporting directives

The first thing you’ll see in that section is a section of comments which include a detailed description of all the Error Level Constants. This is great, because you’ll be using them later on to set your error reporting levels.

Fortunately these constants are also documented in the online PHP Manual, for ease of reference.

Below this list is a second list of Common Values. This shows you how to set some commonly used sets of error reporting value combinations, including the default values, the suggested value for a development environment, and the suggested values for a production environment.

; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

Finally, at the bottom of all the comments is the current value of your error_reporting level. For local development, I’d suggest setting it to E_ALL, so as to see all errors.

error_reporting = E_ALL

This is usually one of the first things I set when I set up a new development environment. That way I’ll see any and all errors that are reported.

After the error_reporting directive, there are some additional directives you can set. As before, the php.ini file includes descriptions of each directive, but I’ll give a brief description of the important ones below.

The display_errors directive allows you to toggle whether PHP outputs the errors or not. I usually have this set to On, so I can see errors as they happen.

display_errors=On

The display_startup_errors allows for the same On/Off toggling of errors that may occur during PHP’s startup sequence. These are typically errors in your PHP or web server configuration, not specifically your code. It’s recommended to leave this Off, unless you’re debugging a problem and you aren’t sure what’s causing it.

The log_errors directive tells PHP whether or not to log errors to an error log file. This is always On by default, and is recommended.

The rest of the directives can be left as the default, except for maybe the error_log directive, which allows you to specify where to log the errors, if log_errors is on. By default it will log the errors wherever your web server has defined them to be logged.

Custom error logging

I use the Apache web server on Ubuntu, and my project-specific virtual host configurations use the following to determine the location for the error log.

ErrorLog ${APACHE_LOG_DIR}/project-error.log

This means it will log to the default Apache log directory, which is /var/log/apache2, under a file called project-error.log. Usually I replace project with the name of the web project it relates to.

So, depending on your local development environment you may need to tweak this to suit your needs. Alternatively, if you can’t change this at the web server level, you can set it at the php.ini level to a specific location.

error_log = /path/to/php.log

It is worth noting that this will log all PHP errors to this file, and if you’re working on multiple projects that might not be ideal. However, always knowing to check that one file for errors might work better for you, so your mileage may vary.

Find and fix those errors

If you’ve recently started coding in PHP, and you decide to turn error reporting on, be prepared to deal with the fallout from your existing code. You may see some things you didn’t expect, and need to fix.

The advantage though, is now that you know how to turn it all on at the server level, you can make sure you see these errors when they happen, and deal with them before someone else sees them!

Oh, and if you were wondering, the errors I was referring to at the start of this post were related to the fact that I was defining constants incorrectly, by not adding quotes around the constant name.

define(CONSTANT, 'Hello world.');

PHP allowed (and might still allow) this, but it would trigger a notice.

Notice: Use of undefined constant CONSTANT - assumed 'CONSTANT' 

This notice was triggered every time I defined a constant, which for that project was about 8 or 9 times. Not great for someone to see 8 or 9 notices at the top of each page…



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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 коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

next →
← prev

The error_reporting() is a pre-defined function of PHP. It allows you to control how many and which PHP errors will be reported. As we already discussed that PHP has several levels of errors. Using the error_reporting() function sets that level for the duration of your current script.

The php.ini file has an error_reporting directive that will be set at runtime by this function.

Syntax

The $level is an optional parameter in error_reporting() function. If the level is not set, this function will return the current error reporting level.

level (Optional)

This parameter specifies the error-report level for the current script.

Return Values

If the level parameter is not given, it will return the current level. Otherwise, it will revert to the old error_reporting level.

Changes

Versions Description
PHP 5.4 E_STRICT has become a part of E_ALL.
PHP 5.3 E_DEPRECATED and E_USER_DEPRECATED are newly added in PHP 5.3. 
PHP 5.2 E_RECOVERABLE_ERROR is added in PHP 5.2.
PHP 5.0 E_STRICT is newly introduced in PHP 5.0.

Example

With the help of PHP program specify different levels of error reporting:

Important Points of error_reporting()

  • By passing zero (0) in error_reporting function, you can remove all errors, warnings, notices, and parse messages. It would be much better to turn off report messages in .htaccess or in ini file instead of having this code in each or every PHP file.
  • PHP allows developers to use undeclared variables. But these undeclared variables can cause problems for the application when used in conditions and loop.
    Sometimes, this could happen that the variable which is declared and being used in conditions or loops have different spellings. So, to display the undeclared variable in the web application, pass the E_NOTICE in the error_reporting function.
  • The error_reporting() function allows the specific error to be displayed, which a user want. Using the ~ character, you can filter the error. For example — ~E_NOTICE means that notices will not be displayed. In the below line of code, all the errors will be displayed except E_NOTICE.
  • Below are the three lines of code given, which works same as the error_reporting(E_ALL) that means it will also display all PHP errors. The error_reporting(E_ALL) is most widely used to display errors because it is easy to read and understand.

Next TopicPHP header()

← prev
next →

error_reporting() in PHP

Introduction to error_reporting() in PHP

In the various levels of errors that PHP has, error_reporting is a function in PHP which indicates what are the errors reported and determines the error_reporting directive during runtime. Using this function we can set the prescribed level for the required duration (usually the runtime) of our script. It returns the old error reporting level based on the input given, or the present reporting level when no parameter is given.

Syntax with Parameters

Following is a syntax with parameters:

Syntax:

error_reporting(level)

Parameters:

There is only a single parameter level which is optional and whose input function takes. It specifies the error reporting level for the present script. Accepted values are constant name and value number.

Note: To ensure compatibility for PHP future versions, named constants are recommended.

There are a few predefined constants whose description is as below:

1. E_Error: These indicate fatal runtime errors that cannot be recovered from and the script execution will be halted.

2. E_Warning: These are non-fatal errors where the execution of the script will continue.

3. E_Parse: This shows compile-time parse errors which are to be generated only by the parsers.

4. E_Notice: This issues runtime notices indicating that the script has found something which shows an error, but which can also happen while running a normal script.

5. E_Core_Error: During PHP’s initial startup there may arise a few fatal errors which are generated by PHP’s core.

6. E_Core_Warning: This shows the non-fatal errors which arise during PHP’s initial startup also generated by PHP’s core.

7. E_Compile_Error: These display fatal errors which occur during compile time. These are generated by the Zend scripting engine.

8. E_Compile_Warning: Similar to above these display compile-time warnings or can be called non-fatal errors and are also generated by Zend scripting engine.

9. E_User_Error: This displays errors generated by the users. This is similar to E_ERROR except that it is generated using PHP function in the PHP code.

10. E_All: This is like a combination of all the above which supports all errors and warnings except that of E_STRICT.

Return Values:

The error_reporting function gives the old reporting level or the present error reporting level if in case no parameters are given.

Working of error_reporting in PHP

This function allows the developer to actually control the different kinds of errors and how many of such errors will be thrown in the application. This function sets an error_reporting directive that will be present in the PHP ini configuration file.

error_reporting(0);
  • When 0 is passed to the error reporting function it removes all warnings, errors, parse related messages and notices, if any. Instead of having to include this line in each of the PHP code files, it is practical to have it added and to turn off these report messages in the ini file present or in the .htaccess.
error_reporting(E_NOTICE);
  • In PHP the variables can be used even when not declared. But this practice is not feasible as the undeclared variables may cause application related issues if it is used in conditional statements and loops. This may also take place because of the spelling mismatch between the declared variables and of that being used for conditions and loops. When this E_NOTICE will be passed into the error_reporting function, only then these undeclared variables will be shown in the web application.
error_reporting(E_ALL & ~E_NOTICE);
  • This error reporting function helps to filter out the errors which can be displayed. The “~” character here means the “not/no” and hence ~E_NOTICE here means to not show any notices. Here the “&” character represents “true for all” whereas “|” means as long as one of the parameters is true. They are exactly similar to the functions AND and OR in PHP.
error_reporting(E_ALL);
error_reporting(-1);
ini_set('error_reporting', E_ALL);
  • All of the above lines serve the same purpose i.e. show all the errors. E_ALL is the most widely used function among all others by developers to display error messages as it is more comprehensible and intelligible.

Error Logging in PHP using error_log() Function

It happens so that during the production phase, error messages are to be hidden from the end-users but this information is needed to be registered for tracing purpose. And the best way to record these errors on the production web application is to write and store in log files.

An easy way to log these is by using the error_log function which takes our parameters as input. The only mandatory parameter here is the first one which contains details about the errors and what all to be logged. Other parameters like the type, destination, and header are non-mandatory here for this function.

error_log("Error found!", 0);
  • The type parameter will be set to 0 by default if not given, and the log information will be appended at the end of the log file generated in the webserver.
error_log("Error information being emailed!", 1, "id@mydomain.com");
  • The type parameter here is 1 will email this log specified in the 3rd parameter which is the email id. For this to work, the PHP ini file must be having a correct SMTP configuration to send out emails. Some of the parameters required for these include host, encryption type, port, password and username.
error_log("Write errors to this file", 3, "https://cdn.educba.com/tmp/errorfile.log");
  • The same error logs can also be written down to the required file whose path will be given in the third parameter. Make sure the given path has all required permissions.

Example of error_reporting() in PHP

Given below is the example:

Code:

<?php
$a = 1;
trigger_error("user warning!", E_USER_WARNING);
$a = 2;
echo "Value of $a is ${$a}";
error_reporting(0);
error_reporting(E_ALL);
?>

Output:

error_reporting in php 1

Advantages of using error_reporting function in PHP

  • error_reporting is good for debugging purposes and for developing web application.
  • Each and every error can be logged and fixed as soon as it happens using this function.
  • To not show it to the end-user, make sure you redirect the errors to a log file while releasing it.

Conclusion

Hence we can say that error_reporting() function in PHP are therefore helpful in cases when there are a lot of problems with the PHP web application and we need to display all of these errors and warnings either for development or debugging purposes. It is a function we can enable different kinds of warnings or error messages and most of them are as discussed above.

Recommended Articles

This is a guide to error_reporting() in PHP. Here we discuss the introduction, working of error_reporting in PHP, error logging in PHP using error_log() function and advantages. You may also have a look at the following articles to learn more –

  1.  PHP Tag in HTML
  2. Validation in PHP
  3. PHP Data Object
  4. PHP Interface

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 коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

Перевод краткого руководства от UX-писателя BBC Эми Лик.

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

Определите, с какой ошибкой столкнулся пользователь

Прежде чем составлять сообщение, убедитесь, что знаете ответы на эти вопросы:

  • Что произошло?
  • Как это случилось?
  • Как это исправить?
  • Ошибся пользователь, система или все вместе?
  • Можно ли изменить текст этого сообщения? Операционная система может контролировать некоторые сообщения об ошибках.

Структура текста

Чтобы исправить ошибку, сначала нужно узнать, в чём она состоит. Сообщение будет выглядеть примерно так: ошибка → как её исправить.

Довольно простая структура. Вот пример реального сообщения об ошибке в одну строчку.

«Файл повреждён. Попробуйте выбрать другой»

Бывает, система не может указать, что именно произошло.

В примере ниже мы специально описываем ошибку в общих чертах. Лучшее, что можно сделать при проблемах с интернетом, — подсказать пользователю, как он может всё исправить.

«Проблема с подключением. Проверьте ваше интернет-соединение и попробуйте снова». Кнопки: «Попробовать снова» и «Отмена»

Пишите коротко и ясно

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

Сообщение должно быть кратким и лаконичным. Избавьтесь от лишних слов, оставьте только нужные. Главное — не перестарайтесь: краткость не должна ставить под угрозу ясность сообщения. Не вырезайте из текста важные детали.

Как надо писать: «“Pictures” уже существует. Выберите другое имя». Как не надо писать: «Не можем переименовать “Pictures”, поскольку файл или папка с таким именем уже существует. Укажите другое имя»

Системная ошибка

Если ошибка произошла по вине системы, извинитесь перед пользователем. Но если в этом виноват пользователь — будьте аккуратны. Извинения звучат неискренне там, где им не место. К тому же неуместные извинения могут сбить с толку — пользователь подумает, что не виноват в ошибке, раз система говорит «простите».

Чтобы принять ответственность за случившееся, используйте активный залог. Пишите: «Мы не можем сохранить ваши изменения», а не «Ваши изменения не могут быть сохранены».

Ошибка пользователя

Иногда ошибки появляются по вине пользователя. Но сообщить об этом можно мягко и без осуждения.

В примере ниже сделали акцент на том, как исправить ситуацию, а не на забывчивости пользователя.

Пишите «Пожалуйста, введите своё имя» вместо обвиняющего «Вы забыли вписать своё имя»

Пассивный залог удобно использовать, когда ошибка произошла по вине пользователя. Он поможет смягчить неприятную ситуацию, например, когда «Ваша карта была отклонена».

Используйте правильный тон

Тон сообщения будет зависеть от серьёзности ошибки. Мягкость в словах отлично подходит для мелких ошибок, но для более критических стоит подбирать слог построже.

Избегайте спецтерминов и всегда изъясняйтесь просто. Пользователь должен чувствовать, что вы стараетесь помочь ему и понятно объяснить, что делать. Помните, мы говорим с людьми, а не с машинами.

Несерьёзное сообщение: «Этот пароль неверный. Попробуйте ещё раз». Серьёзное сообщение: «Эта карта была отклонена. Попробуйте другой способ оплаты»

Пожалуйста, не пытайтесь умничать. Не время для шуток и креатива, когда у пользователя проблема. Шутки или креатив только испортят текст сообщения и усилят чувство разочарования.

Что случится, если нажать на кнопку

Для устранения некоторых ошибок могут потребоваться СТА-кнопка или ссылка. Иногда бывает нужна кнопка отмены.

Всегда объясняйте, что будет, если нажать на кнопку или ссылку. Их текст должен быть понятным, даже если прочитать его отдельно, вне сообщения об ошибке. Это поможет незрячим пользователям перемещаться по интерактивным элементам. Тем, кто бегло прочитал сообщение, тоже будет легче сориентироваться.

Не используйте просто слово «Ок». Что оно значит? С помощью «Ок» можно подтвердить отмену действия или его совершение. Сделайте так, чтобы пользователю было понятно, с чем он соглашается.

Сверху: система пока не может открыть PicEditor, и нужно перезагрузить компьютер, чтобы закончить установку. Кнопка «Окей, перезагрузить» (СТА).  Снизу: недостаточно места, чтобы скачать файл.  Кнопка: «Окей, понятно» (отклонить)

Время и место

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

  1. Что вызывало это сообщение?
  2. Когда оно появилось?
  3. Где появилось?
  4. Понятно ли, с чем оно связано?

Задавая эти вопросы, не забывайте, что есть пользователи с ограниченными возможностями. Это подталкивает к новым вопросам:

  • Как мы можем помочь всем пользователям перейти к решению?
  • Может ли ошибка слишком встревожить пользователя или быть навязчивой, появившись в этот конкретный момент?
  • Как связать сообщение с соответствующим разделом визуально и не визуально?

Помните, что сообщения об ошибках — не барьеры. Они существуют, чтобы расширять возможности, успокаивать и направлять пользователей.

Ключевые рекомендации

  • Определите, с какой ошибкой столкнулся пользователь и как её исправить.
  • Пишите коротко и ясно.
  • Используйте нужный тон и только уместные извинения.
  • Дайте понять, что будет, если нажать на кнопку или ссылку.
  • Учитывайте время и место появления сообщения. Не забывайте про то, как воспримут его пользователи с ограниченными возможностями.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Приложение читай город ошибка 403
  • Пример дисграфических ошибок
  • Пример врачебной ошибки кратко
  • Пример врачебной ошибки стоматолога
  • Приложение фссп не работает ошибка

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: