(PHP 5 >= 5.2.0, PHP 7, PHP 8)
error_get_last —
Получение информации о последней произошедшей ошибке
Описание
error_get_last(): ?array
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает ассоциативный массив с описанием последней произошедшей ошибки.
Ключи массива: «type», «message», «file» и «line». Если ошибка произошла
во внутренней функции PHP, элемент с ключом «message» будет начинаться с
имени этой функции. Возвращает null, если ошибок ещё не произошло.
Примеры
Пример #1 Пример использования error_get_last()
<?php
echo $a;
print_r(error_get_last());
?>
Результатом выполнения данного примера
будет что-то подобное:
Array
(
[type] => 8
[message] => Undefined variable: a
[file] => C:WWWindex.php
[line] => 2
)
Смотрите также
- Константы ошибок
- Переменная $php_errormsg
- error_clear_last() — Очистить самую последнюю ошибку
- Директива
display_errors - Директива
html_errors - Директива
xmlrpc_errors
dmgx dot michael at gmail dot com ¶
12 years ago
If an error handler (see set_error_handler ) successfully handles an error then that error will not be reported by this function.
nicolas dot grekas+php at gmail dot com ¶
9 years ago
[Editor's note: as of PHP 7.0.0 there is error_clear_last() to clear the most recent error.]
To clear error_get_last(), or put it in a well defined state, you should use the code below. It works even when a custom error handler has been set.
<?php
// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@$undef_var;
restore_error_handler();
// error_get_last() is now in a well known state:
// Undefined variable: undef_var
... // Do something
$e = error_get_last();
...
?>
Skrol29 ¶
12 years ago
Function error_get_last() will return an error information even if the error is hidden because you've used character @, because of the "error_reporting" directive in the php.ini file, or because you've used function error_reporting().
Examples:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$y = $x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )
<?php
$y = @$x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )
michael at getsprink dot com ¶
13 years ago
The error_get_last() function will give you the most recent error even when that error is a Fatal error.
Example Usage:
<?php
register_shutdown_function
('handleFatalPhpError');
function
handleFatalPhpError() {
$last_error = error_get_last();
if($last_error['type'] === E_ERROR) {
echo "Can do custom output and/or logging for fatal error here...";
}
}?>
vike2000 at google mail domain ¶
9 years ago
To know if something happened between two statements one can of course use a special string with user_error() (in lieu of a built-in special reset mentioned by mail at mbaierl dot com): <?php
@user_error($error_get_last_mark='error_get_last mark');
$not_set;
$error_get_last=error_get_last();
$something_happened=($error_get_last['message']!=$error_get_last_mark); ?>
If your <?php set_error_handler(function) ?> function returns true then you'll have to roll you own error_get_last functionality. (Shortly mentioned by dmgx dot michael at gmail dot com).
To manual moderators: Re php.net/manual/add-note.php: Since i guess the above technically sorts under "References to other notes" i feel the need to defend myself with that i'm thinking it might show for usability where other's say it fails and no, i haven't got any other medium to reach the readers of the php manual notes.
Also, you could have some examples of what notes you think is okay. Thanks for your moderation.
Brad ¶
14 years ago
Like $php_errormsg, the return value of this function may not be updated if a user-defined error handler returns non-FALSE. Tested on PHP 5.2.6.
<?php
var_dump(PHP_VERSION);
// Outputs: string(5) "5.2.6"@trigger_error("foo");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"set_error_handler(create_function('$a,$b',''));
@
trigger_error("bar");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"set_error_handler(create_function('$a,$b','return false;'));
@
trigger_error("baz");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "baz"
?>
iant at clickwt dot com ¶
13 years ago
Beware that registing a shutdown function to catch errors won't work if other shutdown functions throw errors.
<?php
register_shutdown_function
('cleanupObjects');
register_shutdown_function('handleFatalPhpError');
function
cleanupObjects() {
trigger_error('An insignificant problem', E_USER_WARNING);
}
function
handleFatalPhpError() {
$last_error = error_get_last();
if($last_error['type'] === E_ERROR || $last_error['type'] === E_USER_ERROR) {
echo "Can do custom output and/or logging for fatal error here...";
}
}trigger_error('Something serious', E_USER_ERROR);?>
In the above code, $last_error will contain the warning, becuase cleanupObjects() is called first.
Brad ¶
14 years ago
It can't be completely reset, but you can "clear" it well enough for all practical purposes:
<?php
@trigger_error("");
// do stuff...
$e=error_get_last();
if($e['message']!==''){
// An error occurred
}
?>
php at joert dot net ¶
11 years ago
To simulate this function in a horrid way for php <5.2, you can use something like this.
<?php
if( !function_exists('error_get_last') ) {
set_error_handler(
create_function(
'$errno,$errstr,$errfile,$errline,$errcontext',
'
global $__error_get_last_retval__;
$__error_get_last_retval__ = array(
'type' => $errno,
'message' => $errstr,
'file' => $errfile,
'line' => $errline
);
return false;
'
)
);
function error_get_last() {
global $__error_get_last_retval__;
if( !isset($__error_get_last_retval__) ) {
return null;
}
return $__error_get_last_retval__;
}
}
?>
admin at manomite dot net ¶
5 years ago
This is a simple debugging script for mail functions...
<?php
//Built By Manomite for Debuggingclass Error{
function
__construct(){error_reporting ( E_ALL ^ E_NOTICE );
$err = error_get_last ();
if(
$err){$res = "An error has occurred in your application sir.n Details Include " .$err.""mail("admin@manomite.net","Error Occurred",$res,$from);
}
}
}
?>
scott at eyefruit dot com ¶
12 years ago
If you have the need to check whether an error was a fatal error before PHP 5.2 (in my case, within an output buffer handler), you can use the following hack:
<?php
# Check if there was a PHP fatal error.
# Using error_get_last is the "right" way, but it requires PHP 5.2+. The back-up is a hack.
if (function_exists('error_get_last')) {
$lastPHPError = error_get_last();
$phpFatalError = isset($lastPHPError) && $lastPHPError['type'] === E_ERROR;
} else {
$phpFatalError = strstr($output, '<b>Fatal error</b>:') && ! strstr($output, '</html>');
}
?>
This is, of course, language-dependent, so it wouldn't be good in widely-distributed code, but it may help in certain cases (or at least be the base of something that would work).
mail at mbaierl dot com ¶
14 years ago
This function is pretty useless, as it can not be reset, so there is no way to know if the error really happened on the line before this function call.
phil at wisb dot net ¶
14 years ago
While mail at mbaierl dot com makes the point that this function isn't best for reporting the possible error condition of the most recently executed step, there are situations in which it is especially helpful to know the last error—regardless of when it occurred.
As an example, imagine if you had some code that captured the output from dynamic pages, and cached it for faster delivery to subsequent visitors. A final sanity check would be to see if an error has occurred anywhere during the execution of the script. If there has been an error, we probably don't want to cache that page.
Антон Шевчук // Web-разработчик
Не совершает ошибок только тот, кто ничего не делает, и мы тому пример – трудимся не покладая рук над созданием рабочих мест для тестировщиков 🙂
О да, в этой статье я поведу свой рассказа об ошибках в PHP, и том как их обуздать.
Ошибки
Разновидности в семействе ошибок
Перед тем как приручать ошибки, я бы рекомендовал изучить каждый вид и отдельно обратить внимание на самых ярких представителей.
Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Фатальные ошибки
Самый грозный вид ошибок – фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.
E_PARSE
Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:
<?php
/**
Parse error: syntax error, unexpected end of file
*/
{
Или написали на непонятном языке:
<?php /** Parse error: syntax error, unexpected '...' (T_STRING) */ Тут будет ошибка парсера
Лишние скобочки тоже встречаются, и не важно круглые либо фигурные:
<?php /** Parse error: syntax error, unexpected '}' */ }
Отмечу один важный момент – код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:
<?php
// этот код не сработает
error_reporting(E_ALL);
ini_set('display_errors', 1);
// т.к. вот тут
ошибка парсера
E_ERROR
Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин, так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:
Не был найден подключаемый файл:
/** Fatal error: require_once(): Failed opening required 'not-exists.php' (include_path='.:/usr/share/php:/usr/share/pear') */ require_once 'not-exists.php';
Было брошено исключение (что это за зверь, расскажу немного погодя), но не было обработано:
/** Fatal error: Uncaught exception 'Exception' */ throw new Exception();
При попытке вызвать несуществующий метод класса:
/** Fatal error: Call to undefined method stdClass::notExists() */ $stdClass = new stdClass(); $stdClass->notExists();
Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:
/**
Fatal Error: Allowed Memory Size
*/
$arr = array();
while (true) {
$arr[] = str_pad(' ', 1024);
}
Очень часто происходит при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти
Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug:
/**
Fatal error: Maximum function nesting level of '256' reached, aborting!
*/
function deep() {
deep();
}
deep();
Не фатальные
Данный вид не прерывает выполнение скрипта, но именно их обычно находит тестировщик, и именно они доставляют больше всего хлопот у начинающих разработчиков.
E_WARNING
Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или ошиблись указывая путь к файлу:
/** Warning: include_once(): Failed opening 'not-exists.php' for inclusion */ include_once 'not-exists.php';
Бывает, если используешь неправильный тип аргументов при вызове функций:
/**
Warning: join(): Invalid arguments passed
*/
join('string', 'string');
Их очень много, и перечислять все не имеет смысла…
E_NOTICE
Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.
Когда обращаются к неопределенной переменной:
/** Notice: Undefined variable: a */ echo $a;
Когда обращаются к несуществующему элементу массива:
<?php /** Notice: Undefined index: a */ $b = array(); $b['a'];
Когда обращаются к несуществующей константе:
/** Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT' */ echo UNKNOWN_CONSTANT;
Когда не конвертируют типы данных:
/** Notice: Array to string conversion */ echo array();
Для избежания подобных ошибок – будьте внимательней, и если вам IDE подсказывает о чём-то – не игнорируйте её:

E_STRICT
Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывают. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:
/**
Strict standards: Non-static method Strict::test() should not be called statically
*/
class Strict {
public function test() {
echo 'Test';
}
}
Strict::test();
E_DEPRECATED
Так PHP будет ругаться, если вы используете устаревшие функции (т.е. те, что помечены как deprecated, и в следующем мажорном релизе их не будет):
/**
Deprecated: Function split() is deprecated
*/
// популярная функция, всё никак не удалят из PHP
// deprecated since 5.3
split(',', 'a,b');
В моём редакторе подобные функции будут зачёркнуты:

Обрабатываемые
Этот вид, которые разводит сам разработчик кода, я их уже давно не встречал, не рекомендую их вам заводить:
E_USER_ERROR– критическая ошибкаE_USER_WARNING– не критическая ошибкаE_USER_NOTICE– сообщения которые не являются ошибками
Отдельно стоит отметить E_USER_DEPRECATED – этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():
/**
* @deprecated Deprecated since version 1.2, to be removed in 2.0
*/
function generateToken() {
trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
// ...
// code ...
// ...
}
Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы
display_errors:
- если
display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200- если же
display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок – код будет работать неправильно, но никому об этом не расскажет
Приручение
Для работы с ошибками в PHP существует 3 функции:
- set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
- error_get_last() — получает информацию о последней ошибке
- register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого
Теперь немного подробностей об обработке ошибок с использованием set_error_handler(), в качестве аргументов данная функция принимает имя функции, на которую будет возложена миссия по обработке ошибок и типы ошибок которые будут отслеживаться. Обработчиком ошибок может так же быть методом класса, или анонимной функцией, главное, чтобы он принимал следующий список аргументов:
$errno– первый аргумент содержит тип ошибки в виде целого числа$errstr– второй аргумент содержит сообщение об ошибке$errfile– необязательный третий аргумент содержит имя файла, в котором произошла ошибка$errline– необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка$errcontext– необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка
В случае если обработчик вернул true, то ошибка будет считаться обработанной и выполнение скрипта продолжится, иначе — будет вызван стандартный обработчик, который логирует ошибку и в зависимости от её типа продолжит выполнение скрипта или завершит его. Вот пример обработчика:
<?php
// включаем отображение всех ошибок, кроме E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);
// наш обработчик ошибок
function myHandler($level, $message, $file, $line, $context) {
// в зависимости от типа ошибки формируем заголовок сообщения
switch ($level) {
case E_WARNING:
$type = 'Warning';
break;
case E_NOTICE:
$type = 'Notice';
break;
default;
// это не E_WARNING и не E_NOTICE
// значит мы прекращаем обработку ошибки
// далее обработка ложится на сам PHP
return false;
}
// выводим текст ошибки
echo "<h2>$type: $message</h2>";
echo "<p><strong>File</strong>: $file:$line</p>";
echo "<p><strong>Context</strong>: $". join(', $', array_keys($context))."</p>";
// сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
return true;
}
// регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
set_error_handler('myHandler', E_ALL);
У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет – пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём
С обработчиком, который написан выше есть одна существенная проблема – он не ловит фатальные ошибки, и вместо сайта пользователи увидят лишь пустую страницу, либо, что ещё хуже, сообщение об ошибке. Дабы не допустить подобного сценария следует воспользоваться функцией register_shutdown_function() и с её помощью зарегистрировать функцию, которая всегда будет выполняться по окончанию работы скрипта:
function shutdown() {
echo 'Этот текст будет всегда отображаться';
}
register_shutdown_function('shutdown');
Данная функция будет срабатывать всегда!
Но вернёмся к ошибкам, для отслеживания появления в коде ошибки воспользуемся функцией error_get_last(), с её помощью можно получить информацию о последней выявленной ошибке, а поскольку фатальные ошибки прерывают выполнение кода, то они всегда будут выполнять роль “последних”:
function shutdown() {
$error = error_get_last();
if (
// если в коде была допущена ошибка
is_array($error) &&
// и это одна из фатальных ошибок
in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
) {
// очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
while (ob_get_level()) {
ob_end_clean();
}
// выводим описание проблемы
echo 'Сервер находится на техническом обслуживании, зайдите позже';
}
}
register_shutdown_function('shutdown');
Задание
Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.
О прожорливости
Проведём простой тест, и выясним – сколько драгоценных ресурсов кушает самая тривиальная ошибка:
/**
* Этот код не вызывает ошибок
*/
// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);
$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
$arr[$a] = $i;
}
printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';
В результате запуска данного скрипта у меня получился вот такой результат:
0.002867 seconds 984 bytes
Теперь добавим ошибку в цикле:
/**
* Этот код содержит ошибку
*/
// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);
$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
$arr[$b] = $i; // тут ошиблись с именем переменной
}
printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';
Результат ожидаемо хуже, и на порядок (даже на два порядка!):
0.263645 seconds 992 bytes
Вывод однозначен – ошибки в коде приводят к лишней прожорливости скриптов – так что во время разработки и тестирования приложения включайте отображение всех ошибок!
Тестирование проводил на PHP версии 5.6, в седьмой версии результат лучше – 0.0004 секунды против 0.0050 – разница только на один порядок, но в любом случае результат стоит прикладываемых усилий по исправлению ошибок
Где собака зарыта
В PHP есть спец символ «@» – оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:
<?php
echo @UNKNOWN_CONSTANT;
При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.
Если вы в такой способ подавляете ошибки, то это уменьшает нагрузку на процессор в сравнении с тем, если вы их просто скрываете (см. сравнительный тест выше), но в любом случае, подавление ошибок это зло
Исключения
В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Думаю да, ведь это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений
Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.
К примеру, скрипт должен сохранить какие-то данные в кеш файл, если что-то пошло не так (нет доступа на запись, нет места на диске), генерируется исключение соответствующего типа, а в обработчике исключений принимается решение – сохранить в другое место или сообщить пользователю о проблеме.
Исключение – это объект который наследуется от класса Exception, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, “бросить”) при помощи оператора throw, и можно перехватить (“поймать”) оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:
try {
// код который может выбросить исключение
if (rand(0, 1)) {
throw new Exception('One')
} else {
echo 'Zero';
}
} catch (Exception $e) {
// код который может обработать исключение
echo $e->getMessage();
}
В каких случаях стоит применять исключения:
- если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
- если используемый вами фреймверк или библиотека декларируют их использование
Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл – помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:
$directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';
// директории может не быть
if (!is_dir($directory)) {
throw new Exception('Directory `logs` is not exists');
}
// может не быть прав на запись в директорию
if (!is_writable($directory)) {
throw new Exception('Directory `logs` is not writable');
}
// возможно кто-то уже создал файл, и закрыл к нему доступ
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
throw new Exception('System can't create log file');
}
fputs($file, date('[H:i:s]') . " donen");
fclose($file);
Соответственно ловить данные исключения будем примерно так:
try {
// код который пишет в файл
// ...
} catch (Exception $e) {
// выводим текст ошибки
echo 'Не получилось: '. $e->getMessage();
}
В данном примере приведен очень простой сценарий обработки исключений, когда у нас любая исключительная ситуация обрабатывается на один манер. Но зачастую – различные исключения требуют различного подхода к обработке, и тогда следует использовать коды исключений и задать иерархию исключений в приложении:
// исключения файловой системы
class FileSystemException extends Exception {}
// исключения связанные с директориями
class DirectoryException extends FileSystemException {
// коды исключений
const DIRECTORY_NOT_EXISTS = 1;
const DIRECTORY_NOT_WRITABLE = 2;
}
// исключения связанные с файлами
class FileException extends FileSystemException {}
Теперь, если использовать эти исключения то можно получить следующий код:
try {
// код который пишет в файл
if (!is_dir($directory)) {
throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
}
if (!is_writable($directory)) {
throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
}
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
throw new FileException('System can't open log file');
}
fputs($file, date('[H:i:s]'') . " donen");
fclose($file);
} catch (DirectoryException $e) {
echo 'С директорией возникла проблема: '. $e->getMessage();
} catch (FileException $e) {
echo 'С файлом возникла проблема: '. $e->getMessage();
} catch (FileSystemException $e) {
echo 'Ошибка файловой системы: '. $e->getMessage();
} catch (Exception $e) {
echo 'Ошибка сервера: '. $e->getMessage();
}
Важно помнить, что Exception — это прежде всего исключительное событие, иными словами исключение из правил. Не нужно использовать их для обработки очевидных ошибок, к примеру, для валидации введённых пользователем данных (хотя тут не всё так однозначно). При этом обработчик исключений должен быть написан в том месте, где он будет способен его обработать. К примеру, обработчик для исключений вызванных недоступностью файла для записи должен быть в методе, который отвечает за выбор файла или методе его вызывающем, для того что бы он имел возможность выбрать другой файл или другую директорию.
Так, а что будет если не поймать исключение? Вы получите “Fatal Error: Uncaught exception …”. Неприятно.
Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:
// в качестве обработчика событий
// будем использовать анонимную функцию
set_exception_handler(function($exception) {
/** @var Exception $exception */
echo $exception->getMessage(), "<br/>n";
echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
echo $exception->getTraceAsString(), "<br/>n";
});
Ещё расскажу про конструкцию с использованием блока finally – этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:
try {
// код который может выбросить исключение
} catch (Exception $e) {
// код который может обработать исключение
// если конечно оно появится
} finally {
// код, который будет выполнен при любом раскладе
}
Для понимания того, что это нам даёт приведу следующий пример использования блока finally:
try {
// где-то глубоко внутри кода
// соединение с базой данных
$handler = mysqli_connect('localhost', 'root', '', 'test');
try {
// при работе с БД возникла исключительная ситуация
// ...
throw new Exception('DB error');
} catch (Exception $e) {
// исключение поймали, обработали на своём уровне
// и должны его пробросить вверх, для дальнейшей обработки
throw new Exception('Catch exception', 0, $e);
} finally {
// но, соединение с БД необходимо закрыть
// будем делать это в блоке finally
mysqli_close($handler);
}
// этот код не будет выполнен, если произойдёт исключение в коде выше
echo "Ok";
} catch (Exception $e) {
// ловим исключение, и выводим текст
echo $e->getMessage();
echo "<br/>";
// выводим информацию о первоначальном исключении
echo $e->getPrevious()->getMessage();
}
Т.е. запомните – блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).
Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код 😉
Задание
Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира – посмотрите как это круто выглядит у whoops.
PHP7 – всё не так, как было раньше
Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы столкнётесь через год работы PHP разработчиком. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот – в PHP7 это решили исправить, но как обычно завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:
- при возникновении фатальных ошибок типа
E_ERRORили фатальных ошибок с возможностью обработкиE_RECOVERABLE_ERRORPHP выбрасывает исключение - эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
- эти исключения наследуют класс Error
- оба класса Exception и Error реализуют интерфейс Throwable
- вы не можете реализовать интерфейс Throwable в своём коде
Интерфейс Throwable практически полностью повторяет нам Exception:
interface Throwable
{
public function getMessage(): string;
public function getCode(): int;
public function getFile(): string;
public function getLine(): int;
public function getTrace(): array;
public function getTraceAsString(): string;
public function getPrevious(): Throwable;
public function __toString(): string;
}
Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:
try {
// файл, который вызывает ошибку парсера
include 'e_parse_include.php';
} catch (Error $e) {
var_dump($e);
}
В результате ошибку поймаем и выведем:
object(ParseError)#1 (7) {
["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
["string":"Error":private] => string(0) ""
["code":protected] => int(0)
["file":protected] => string(49) "/www/education/error/e_parse_include.php"
["line":protected] => int(4)
["trace":"Error":private] => array(0) { }
["previous":"Error":private] => NULL
}
Как видите – поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть другие, но не буду мучать – для наглядности приведу иерархию исключений:
interface Throwable
|- Exception implements Throwable
| |- ErrorException extends Exception
| |- ... extends Exception
| `- ... extends Exception
`- Error implements Throwable
|- TypeError extends Error
|- ParseError extends Error
|- ArithmeticError extends Error
| `- DivisionByZeroError extends ArithmeticError
`- AssertionError extends Error
TypeError – для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:
try {
(function(int $one, int $two) {
return;
})('one', 'two');
} catch (TypeError $e) {
echo $e->getMessage();
}
ArithmeticError – могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:
try {
1 << -1;
} catch (ArithmeticError $e) {
echo $e->getMessage();
}
DivisionByZeroError – ошибка деления на ноль:
try {
1 / 0;
} catch (ArithmeticError $e) {
echo $e->getMessage();
}
AssertionError – редкий зверь, появляется когда условие заданное в assert() не выполняется:
ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
try {
assert(1 === 0);
} catch (AssertionError $e) {
echo $e->getMessage();
}
При настройках production-серверов, директивы
zend.assertionsиassert.exceptionотключают, и это правильно
Задание
Написать универсальный обработчик ошибок для PHP7, который будет отлавливать все возможные исключения.
При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7
Отладка
Иногда для отладки кода нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:
<?php
function example() {
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
}
class ExampleClass {
public static function method () {
example();
}
}
ExampleClass::method();
В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:
#0 example() called at [/www/education/error/backtrace.php:10] #1 ExampleClass::method() called at [/www/education/error/backtrace.php:14]
Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.
Assert
Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP, собственно это кусочек контрактной методологии программирования, и дальше я расскажу вам как я никогда его не использовал 🙂
Первый случай – это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:
// включаем вывод ошибок
error_reporting(E_ALL);
ini_set('display_errors', 1);
// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);
assert(false, "Remove it!");
В результате выполнения данного кода получим E_WARNING:
Warning: assert(): Remove it! failed
PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:
// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);
// переключаем на исключения
ini_set('assert.exception', 1);
assert(false, "Remove it!");
В результате ожидаемо получаем не пойманный AssertionError. При необходимости, можно выбрасывать произвольное исключение:
assert(false, new Exception("Remove it!"));
Но я бы рекомендовал использовать метки
@TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними
Второй вариант использования – это создание некоего подобия TDD, но помните – это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:
// callback-функция для вывода информации в браузер
function backlog($script, $line, $code, $message) {
echo "<h3>$message</h3>";
highlight_string ($code);
}
// устанавливаем callback-функцию
assert_options(ASSERT_CALLBACK, 'backlog');
// отключаем вывод предупреждений
assert_options(ASSERT_WARNING, false);
// пишем проверку и её описание
assert("sqr(4) == 16", "When I send integer, function should return square of it");
// функция, которую проверяем
function sqr($a) {
return; // она не работает
}
Третий теоретический вариант – это непосредственно контрактное программирование – когда вы описали правила использования своей библиотеки, но хотите точно убедится, что вас поняли правильно, и в случае чего сразу указать разработчику на ошибку (я вот даже не уверен, что правильно его понимаю, но пример кода вполне рабочий):
/**
* Настройки соединения должны передаваться в следующем виде
*
* [
* 'host' => 'localhost',
* 'port' => 3306,
* 'name' => 'dbname',
* 'user' => 'root',
* 'pass' => ''
* ]
*
* @param $settings
*/
function setupDb ($settings) {
// проверяем настройки
assert(isset($settings['host']), 'Db `host` is required');
assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
assert(isset($settings['name']), 'Db `name` is required, should be integer');
// соединяем с БД
// ...
}
setupDb(['host' => 'localhost']);
Никогда не используйте
assert()для проверки входных параметров, ведь фактическиassert()интерпретирует строковую переменную (ведёт себя какeval()), а это чревато PHP-инъекцией. И да, это правильное поведение, т.к. просто отключив assert’ы всё что передаётся внутрь будет проигнорировано, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения
Если у вас есть живой опыт использования assert() – поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме – PHP Assertions, с таким же вопросом в конце 🙂
В заключение
Я за вас напишу выводы из данной статьи:
- Ошибкам бой – их не должно быть в вашем коде
- Используйте исключения – работу с ними нужно правильно организовать и будет счастье
- Assert – узнали о них, и хорошо
P.S. Спасибо Максиму Слесаренко за помощь в написании статьи
shawing at gmail dot com ¶
18 years ago
Although the root user writes to the files 'error_log' and 'access_log', the Apache user has to own the file referenced by 'error_log = filename' or no log entries will be written.
; From php.ini
; Log errors to specified file.
error_log = /usr/local/apache/logs/php.errors
[root@www logs]$ ls -l /usr/local/apache/logs/php.errors
-rw-r--r-- 1 nobody root 27K Jan 27 16:58 php.errors
tracerdx at tracerdx dot com ¶
17 years ago
I keep seeing qualification lists for error types/error-nums as arrays; In user notes and in the manual itself. For example, in this manual entry's example, when trying to seperate behavior for the variable trace in the error report:
<?php //...
// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);//and later...if (in_array($errno, $user_errors)) {
//...whatever
}//... ?>
I was under the impression that PHP error code values where bitwise flag values. Wouldn't bitwise masking be better? So I propose a slightly better way:
<?php //...$user_errors = E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE;//...blah...if ($errno & $user_errors) {
//...whatever
}//... ?>
Or for those of you who don't like the idea of using an integer as the condition in an if statement:
<?php
if (($errno & $user_errors) > 0) {
//...whatever
}
?>
I think that's much more efficient than using _yet another_ array() constuct and an in_array().
If I am wrong, and the E_* constants aren't supposed to be used in this fashion (ie, the constans aren't guaranteed to be bitwise, which would be odd since that's how they're setup in the php.ini file), then delete me. I just don't see why one should be using arrays when bitwise comparisons will work, considering the bitwise method should be MUCH more efficient.
ptah at se dot linux dot org ¶
18 years ago
PHP5 only (only tested with php5.0).
If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.
Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"
This error is not particulary informative, is it? :)
This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
private $context = null;
public function __construct
($code, $message, $file, $line, $context = null)
{
parent::__construct($message, $code);
$this->file = $file;
$this->line = $line;
$this->context = $context;
}
};
function
error_handler($code, $message, $file, $line) {
throw new PHPErrorException($code, $message, $file, $line);
}
function
exception_handler(Exception $e)
{
$errors = array(
E_USER_ERROR => "User Error",
E_USER_WARNING => "User Warning",
E_USER_NOTICE => "User Notice",
);
echo
$errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
' on line '.$e->getLine()."n";
echo $e->getTraceAsString();
}set_error_handler('error_handler');
set_exception_handler('exception_handler');// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>
There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.
So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.
regards, C-A B.
Stephen ¶
16 years ago
If you are using PHP as an Apache module, your default behavior may be to write PHP error messages to Apache's error log. This is because the error_log .ini directive may be set equal to "error_log" which is also the name of Apache's error log. I think this is intentional.
However, you can separate Apache errors from PHP errors if you wish by simply setting a different value for error_log. I write mine in the /var/log folder.
mortonda at dgrmm dot net ¶
16 years ago
Note the example code listed here calls date() every time this is called. If you have a complex source base which calls the custom error handler often, it can end up taking quite a bit of time. I ran a profiler on som code and discovered that 50% of the time was spent in the date function in this error handler.
Anonymous ¶
17 years ago
When configuring your error log file in php.ini, you can use an absolute path or a relative path. A relative path will be resolved based on the location of the generating script, and you'll get a log file in each directory you have scripts in. If you want all your error messages to go to the same file, use an absolute path to the file.
In some application development methodologies, there is the concept of an application root directory, indicated by "/" (even on Windows). However, PHP does not seem to have this concept, and using a "/" as the initial character in a log file path produces weird behavior on Windows.
If you are running on Windows and have set, in php.ini:
error_log = "/php_error.log"
You will get some, but not all, error messages. The file will appear at
c:php_error.log
and contain internally generated error messages, making it appear that error logging is working. However, log messages requested by error_log() do NOT appear here, or anywhere else, making it appear that the code containing them did not get processed.
Apparently on Windows the internally generated errors will interpret "/" as "C:" (or possibly a different drive if you have Windows installed elsewhere - I haven't tested this). However, the error_log process apparently can't find "/" - understandably enough - and the message is dropped silently.
theotek AT nowhere DOT org ¶
16 years ago
It is totally possible to use debug_backtrace() inside an error handling function. Here, take a look:
<?php
set_error_handler('errorHandler');
function
errorHandler( $errno, $errstr, $errfile, $errline, $errcontext)
{
echo 'Into '.__FUNCTION__.'() at line '.__LINE__.
"nn---ERRNO---n". print_r( $errno, true).
"nn---ERRSTR---n". print_r( $errstr, true).
"nn---ERRFILE---n". print_r( $errfile, true).
"nn---ERRLINE---n". print_r( $errline, true).
"nn---ERRCONTEXT---n".print_r( $errcontext, true).
"nnBacktrace of errorHandler()n".
print_r( debug_backtrace(), true);
}
function
a( )
{
//echo "a()'s backtracen".print_r( debug_backtrace(), true);
asdfasdf; // oops
}
function
b()
{
//echo "b()'s backtracen".print_r( debug_backtrace(), true);
a();
}b();
?>
Outputs:
<raw>
Into errorhandler() at line 9
---ERRNO---
8
---ERRSTR---
Use of undefined constant asdfasdf - assumed 'asdfasdf'
---ERRFILE---
/home/theotek/test-1.php
---ERRLINE---
23
---ERRCONTEXT---
Array
(
)
Backtrace of errorHandler()
Array
(
[0] => Array
(
[function] => errorhandler
[args] => Array
(
[0] => 8
[1] => Use of undefined constant asdfasdf - assumed 'asdfasdf'
[2] => /home/theotek/test-1.php
[3] => 23
[4] => Array
(
)
)
)
[1] => Array
(
[file] => /home/theotek/test-1.php
[line] => 23
[function] => a
)
[2] => Array
(
[file] => /home/theotek/test-1.php
[line] => 30
[function] => a
[args] => Array
(
)
)
[3] => Array
(
[file] => /home/theotek/test-1.php
[line] => 33
[function] => b
[args] => Array
(
)
)
)
</raw>
So, the first member of the backtrace's array is not really surprising, except from the missing "file" and "line" members.
The second member of the backtrace seem the be a hook inside the zend engine that is used to trigger the error.
Other members are the normal backtrace.
jbq at caraldi dot com ¶
15 years ago
Precision about error_log when configured with syslog: the syslog() call is done with severity NOTICE.
petrov dot michael () gmail com ¶
16 years ago
I have found that on servers that enforce display_errors to be off it is very inconvenient to debug syntax errors since they cause fatal startup errors. I have used the following method to bypass this limitation:
The syntax error is inside the file "syntax.php", therefore I create a file "syntax.debug.php" with the following code:
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
include(
'syntax.php');
?>
The 5 line file is guaranteed to be free of errors, allowing PHP to execute the directives within it before including the file which previously caused fatal startup errors. Now those fatal startup errors become run time fatal errors.
This always works for me:
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:
display_errors = on
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
php_flag display_errors 1
anthonyryan1
4,6472 gold badges33 silver badges27 bronze badges
answered Jan 29, 2014 at 11:25
![]()
Fancy JohnFancy John
37.4k3 gold badges26 silver badges25 bronze badges
16
You can’t catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.
This question may provide additional info.
answered Jun 27, 2009 at 19:14
Michael MadsenMichael Madsen
53.8k7 gold badges72 silver badges83 bronze badges
0
Inside your php.ini:
display_errors = on
Then restart your web server.
j0k
22.4k28 gold badges80 silver badges88 bronze badges
answered Jan 8, 2013 at 9:27
user1803477user1803477
1,5951 gold badge9 silver badges4 bronze badges
5
To display all errors you need to:
1. Have these lines in the PHP script you’re calling from the browser (typically index.php):
error_reporting(E_ALL);
ini_set('display_errors', '1');
2.(a) Make sure that this script has no syntax errors
—or—
2.(b) Set display_errors = On in your php.ini
Otherwise, it can’t even run those 2 lines!
You can check for syntax errors in your script by running (at the command line):
php -l index.php
If you include the script from another PHP script then it will display syntax errors in the included script. For example:
index.php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Any syntax errors here will result in a blank screen in the browser
include 'my_script.php';
my_script.php
adjfkj // This syntax error will be displayed in the browser
answered Jan 29, 2014 at 9:52
andreandre
1,8311 gold badge16 silver badges8 bronze badges
2
Some web hosting providers allow you to change PHP parameters in the .htaccess file.
You can add the following line:
php_value display_errors 1
I had the same issue as yours and this solution fixed it.
![]()
answered May 18, 2013 at 15:01
KalhuaKalhua
5614 silver badges2 bronze badges
1
You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:
try{
// Your code
}
catch(Error $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):
try{
// Your code
}
catch(Throwable $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
answered Mar 28, 2016 at 19:26
![]()
Frank ForteFrank Forte
1,89718 silver badges18 bronze badges
9
This will work:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
![]()
answered May 5, 2014 at 13:23
![]()
Mahendra JellaMahendra Jella
5,2801 gold badge32 silver badges38 bronze badges
1
Use:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:
php -l phpfilename.php
![]()
answered May 4, 2016 at 19:14
Abhijit JagtapAbhijit Jagtap
2,6852 gold badges32 silver badges43 bronze badges
0
Set this in your index.php file:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
![]()
answered Sep 26, 2017 at 12:32
![]()
Sumit GuptaSumit Gupta
5694 silver badges12 bronze badges
0
Create a file called php.ini in the folder where your PHP file resides.
Inside php.ini add the following code (I am giving an simple error showing code):
display_errors = on
display_startup_errors = on
![]()
answered Mar 31, 2015 at 18:38
NavyaKumarNavyaKumar
5895 silver badges3 bronze badges
As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHP 7.
On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.
Here three pieces of code:
File: tst1.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Missing " and ;
echo "Testing
?>
Running this in PHP 7 will show nothing.
Now, try this:
File: tst2.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include ("tst3.php");
?>
File: tst3.php
<?php
// Missing " and ;
echo "Testing
?>
Now run tst2 which sets the error reporting, and then include tst3. You will see:
Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4
![]()
answered May 20, 2017 at 12:07
PeterPeter
1,23318 silver badges32 bronze badges
2
I would usually go with the following code in my plain PHP projects.
if(!defined('ENVIRONMENT')){
define('ENVIRONMENT', 'DEVELOPMENT');
}
$base_url = null;
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'DEVELOPMENT':
$base_url = 'http://localhost/product/';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL|E_STRICT);
break;
case 'PRODUCTION':
$base_url = 'Production URL'; /* https://google.com */
error_reporting(0);
/* Mechanism to log errors */
break;
default:
exit('The application environment is not set correctly.');
}
}
answered Feb 1, 2017 at 7:16
If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');
Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:
//file1.php
namespace ab;
class x {
...
}
//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
...
}
answered Apr 24, 2015 at 2:55
jxmallettjxmallett
4,0471 gold badge28 silver badges35 bronze badges
2
If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:
find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"
If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:
<?php
if( !ini_set( 'display_errors', 1 ) ) {
echo "display_errors cannot be set.";
} else {
echo "changing display_errors via script is possible.";
}
answered Jan 11, 2016 at 12:11
chiborgchiborg
26.1k12 gold badges98 silver badges114 bronze badges
1
You can do something like below:
Set the below parameters in your main index file:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
Then based on your requirement you can choose which you want to show:
For all errors, warnings and notices:
error_reporting(E_ALL); OR error_reporting(-1);
For all errors:
error_reporting(E_ERROR);
For all warnings:
error_reporting(E_WARNING);
For all notices:
error_reporting(E_NOTICE);
For more information, check here.
![]()
answered Feb 1, 2017 at 7:33
![]()
Binit GhetiyaBinit Ghetiya
1,8612 gold badges23 silver badges31 bronze badges
1
You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.
function ERR_HANDLER($errno, $errstr, $errfile, $errline){
$msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
<b>File:</b> $errfile <br>
<b>Line:</b> $errline <br>
<pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";
echo $msg;
return false;
}
function EXC_HANDLER($exception){
ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}
function shutDownFunction() {
$error = error_get_last();
if ($error["type"] == 1) {
ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
}
}
set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");
![]()
answered Jun 4, 2017 at 14:41
lintabálintabá
7319 silver badges18 bronze badges
Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:
display_errors = on
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log
answered Jan 8, 2022 at 22:17
![]()
This code on top should work:
error_reporting(E_ALL);
However, try to edit the code on the phone in the file:
error_reporting =on
![]()
answered May 9, 2017 at 3:28
![]()
Joel WemboJoel Wembo
8146 silver badges10 bronze badges
The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.
try {
// Page code
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n";
}
![]()
answered Mar 27, 2017 at 2:31
![]()
XakiruXakiru
2,4111 gold badge14 silver badges11 bronze badges
1
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.
![]()
answered May 24, 2018 at 8:48
pardeeppardeep
3511 gold badge5 silver badges7 bronze badges
0
Just write:
error_reporting(-1);
answered Jan 13, 2017 at 18:56
![]()
jewelhuqjewelhuq
1,19214 silver badges19 bronze badges
0
You can do this by changing the php.ini file and add the following
display_errors = on
display_startup_errors = on
OR you can also use the following code as this always works for me
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Apr 11, 2019 at 8:43
![]()
0
If you have Xdebug installed you can override every setting by setting:
xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;
force_display_errors
Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.force_error_reporting
Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().
![]()
answered Oct 19, 2017 at 5:45
You might want to use this code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
![]()
baduker
17.2k9 gold badges31 silver badges51 bronze badges
answered Mar 28, 2019 at 12:42
Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
Display all PHP errors
error_reporting(E_ALL); or ini_set('error_reporting', E_ALL);
Turn off all error reporting
error_reporting(0);
answered Dec 31, 2019 at 10:07
![]()
If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:
php -ddisplay_errors=1 script.php
![]()
answered Oct 24, 2019 at 23:11
gvlasovgvlasov
17.7k19 gold badges69 silver badges106 bronze badges
error_reporting(1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
Put this at the top of your page.
answered Feb 28, 2021 at 0:51
![]()
KwedKwed
2313 silver badges4 bronze badges
Input this on the top of your code
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
And in the php.ini file, insert this:
display_errors = on
This must work.
answered Aug 23, 2021 at 21:22
![]()
You can show Php error in your display via simple ways.
Firstly, just put this below code in your php.ini file.
display_errors = on;
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
php_flag display_errors 1
OR you can also use the following code in your index.php file
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Nov 6, 2020 at 6:41
![]()
In Unix CLI, it’s very practical to redirect only errors to a file:
./script 2> errors.log
From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:
fwrite(STDERR, "Debug infosn"); // Write in errors.log^
Then from another shell, for live changes:
tail -f errors.log
or simply
watch cat errors.log
answered Nov 26, 2019 at 2:28
![]()
NVRMNVRM
10.5k1 gold badge82 silver badges85 bronze badges
2
This always works for me:
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:
display_errors = on
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
php_flag display_errors 1
anthonyryan1
4,6472 gold badges33 silver badges27 bronze badges
answered Jan 29, 2014 at 11:25
![]()
Fancy JohnFancy John
37.4k3 gold badges26 silver badges25 bronze badges
16
You can’t catch parse errors when enabling error output at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.
This question may provide additional info.
answered Jun 27, 2009 at 19:14
Michael MadsenMichael Madsen
53.8k7 gold badges72 silver badges83 bronze badges
0
Inside your php.ini:
display_errors = on
Then restart your web server.
j0k
22.4k28 gold badges80 silver badges88 bronze badges
answered Jan 8, 2013 at 9:27
user1803477user1803477
1,5951 gold badge9 silver badges4 bronze badges
5
To display all errors you need to:
1. Have these lines in the PHP script you’re calling from the browser (typically index.php):
error_reporting(E_ALL);
ini_set('display_errors', '1');
2.(a) Make sure that this script has no syntax errors
—or—
2.(b) Set display_errors = On in your php.ini
Otherwise, it can’t even run those 2 lines!
You can check for syntax errors in your script by running (at the command line):
php -l index.php
If you include the script from another PHP script then it will display syntax errors in the included script. For example:
index.php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Any syntax errors here will result in a blank screen in the browser
include 'my_script.php';
my_script.php
adjfkj // This syntax error will be displayed in the browser
answered Jan 29, 2014 at 9:52
andreandre
1,8311 gold badge16 silver badges8 bronze badges
2
Some web hosting providers allow you to change PHP parameters in the .htaccess file.
You can add the following line:
php_value display_errors 1
I had the same issue as yours and this solution fixed it.
![]()
answered May 18, 2013 at 15:01
KalhuaKalhua
5614 silver badges2 bronze badges
1
You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:
try{
// Your code
}
catch(Error $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):
try{
// Your code
}
catch(Throwable $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
answered Mar 28, 2016 at 19:26
![]()
Frank ForteFrank Forte
1,89718 silver badges18 bronze badges
9
This will work:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
![]()
answered May 5, 2014 at 13:23
![]()
Mahendra JellaMahendra Jella
5,2801 gold badge32 silver badges38 bronze badges
1
Use:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:
php -l phpfilename.php
![]()
answered May 4, 2016 at 19:14
Abhijit JagtapAbhijit Jagtap
2,6852 gold badges32 silver badges43 bronze badges
0
Set this in your index.php file:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
![]()
answered Sep 26, 2017 at 12:32
![]()
Sumit GuptaSumit Gupta
5694 silver badges12 bronze badges
0
Create a file called php.ini in the folder where your PHP file resides.
Inside php.ini add the following code (I am giving an simple error showing code):
display_errors = on
display_startup_errors = on
![]()
answered Mar 31, 2015 at 18:38
NavyaKumarNavyaKumar
5895 silver badges3 bronze badges
As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHP 7.
On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.
Here three pieces of code:
File: tst1.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Missing " and ;
echo "Testing
?>
Running this in PHP 7 will show nothing.
Now, try this:
File: tst2.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include ("tst3.php");
?>
File: tst3.php
<?php
// Missing " and ;
echo "Testing
?>
Now run tst2 which sets the error reporting, and then include tst3. You will see:
Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4
![]()
answered May 20, 2017 at 12:07
PeterPeter
1,23318 silver badges32 bronze badges
2
I would usually go with the following code in my plain PHP projects.
if(!defined('ENVIRONMENT')){
define('ENVIRONMENT', 'DEVELOPMENT');
}
$base_url = null;
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'DEVELOPMENT':
$base_url = 'http://localhost/product/';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL|E_STRICT);
break;
case 'PRODUCTION':
$base_url = 'Production URL'; /* https://google.com */
error_reporting(0);
/* Mechanism to log errors */
break;
default:
exit('The application environment is not set correctly.');
}
}
answered Feb 1, 2017 at 7:16
If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');
Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:
//file1.php
namespace ab;
class x {
...
}
//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
...
}
answered Apr 24, 2015 at 2:55
jxmallettjxmallett
4,0471 gold badge28 silver badges35 bronze badges
2
If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:
find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"
If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:
<?php
if( !ini_set( 'display_errors', 1 ) ) {
echo "display_errors cannot be set.";
} else {
echo "changing display_errors via script is possible.";
}
answered Jan 11, 2016 at 12:11
chiborgchiborg
26.1k12 gold badges98 silver badges114 bronze badges
1
You can do something like below:
Set the below parameters in your main index file:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
Then based on your requirement you can choose which you want to show:
For all errors, warnings and notices:
error_reporting(E_ALL); OR error_reporting(-1);
For all errors:
error_reporting(E_ERROR);
For all warnings:
error_reporting(E_WARNING);
For all notices:
error_reporting(E_NOTICE);
For more information, check here.
![]()
answered Feb 1, 2017 at 7:33
![]()
Binit GhetiyaBinit Ghetiya
1,8612 gold badges23 silver badges31 bronze badges
1
You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.
function ERR_HANDLER($errno, $errstr, $errfile, $errline){
$msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
<b>File:</b> $errfile <br>
<b>Line:</b> $errline <br>
<pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";
echo $msg;
return false;
}
function EXC_HANDLER($exception){
ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}
function shutDownFunction() {
$error = error_get_last();
if ($error["type"] == 1) {
ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
}
}
set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");
![]()
answered Jun 4, 2017 at 14:41
lintabálintabá
7319 silver badges18 bronze badges
Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:
display_errors = on
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log
answered Jan 8, 2022 at 22:17
![]()
This code on top should work:
error_reporting(E_ALL);
However, try to edit the code on the phone in the file:
error_reporting =on
![]()
answered May 9, 2017 at 3:28
![]()
Joel WemboJoel Wembo
8146 silver badges10 bronze badges
The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.
try {
// Page code
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n";
}
![]()
answered Mar 27, 2017 at 2:31
![]()
XakiruXakiru
2,4111 gold badge14 silver badges11 bronze badges
1
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.
![]()
answered May 24, 2018 at 8:48
pardeeppardeep
3511 gold badge5 silver badges7 bronze badges
0
Just write:
error_reporting(-1);
answered Jan 13, 2017 at 18:56
![]()
jewelhuqjewelhuq
1,19214 silver badges19 bronze badges
0
You can do this by changing the php.ini file and add the following
display_errors = on
display_startup_errors = on
OR you can also use the following code as this always works for me
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Apr 11, 2019 at 8:43
![]()
0
If you have Xdebug installed you can override every setting by setting:
xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;
force_display_errors
Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.force_error_reporting
Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().
![]()
answered Oct 19, 2017 at 5:45
You might want to use this code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
![]()
baduker
17.2k9 gold badges31 silver badges51 bronze badges
answered Mar 28, 2019 at 12:42
Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
Display all PHP errors
error_reporting(E_ALL); or ini_set('error_reporting', E_ALL);
Turn off all error reporting
error_reporting(0);
answered Dec 31, 2019 at 10:07
![]()
If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:
php -ddisplay_errors=1 script.php
![]()
answered Oct 24, 2019 at 23:11
gvlasovgvlasov
17.7k19 gold badges69 silver badges106 bronze badges
error_reporting(1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
Put this at the top of your page.
answered Feb 28, 2021 at 0:51
![]()
KwedKwed
2313 silver badges4 bronze badges
Input this on the top of your code
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
And in the php.ini file, insert this:
display_errors = on
This must work.
answered Aug 23, 2021 at 21:22
![]()
You can show Php error in your display via simple ways.
Firstly, just put this below code in your php.ini file.
display_errors = on;
(if you don’t have access to php.ini, then putting this line in .htaccess might work too):
php_flag display_errors 1
OR you can also use the following code in your index.php file
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Nov 6, 2020 at 6:41
![]()
In Unix CLI, it’s very practical to redirect only errors to a file:
./script 2> errors.log
From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:
fwrite(STDERR, "Debug infosn"); // Write in errors.log^
Then from another shell, for live changes:
tail -f errors.log
or simply
watch cat errors.log
answered Nov 26, 2019 at 2:28
![]()
NVRMNVRM
10.5k1 gold badge82 silver badges85 bronze badges
2
PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:
E_ALL– все ошибки,E_ERROR– критические ошибки,E_WARNING– предупреждения,E_PARSE– ошибки синтаксиса,E_NOTICE– замечания,E_CORE_ERROR– ошибки обработчика,E_CORE_WARNING– предупреждения обработчика,E_COMPILE_ERROR– ошибки компилятора,E_COMPILE_WARNING– предупреждения компилятора,E_USER_ERROR– ошибки пользователей,E_USER_WARNING– предупреждения пользователей,E_USER_NOTICE– уведомления пользователей.
1
Вывод ошибок в браузере
error_reporting(E_ALL);
ini_set('display_errors', 'On');
PHP
В htaccess
php_value error_reporting "E_ALL"
php_flag display_errors On
htaccess
На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.
2
Запись ошибок в лог файл
error_reporting(E_ALL);
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');
PHP
Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:
Order Allow,Deny
Deny from all
htaccess
Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):
<FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
Order Allow,Deny
Deny from all
</FilesMatch>
htaccess
3
Отправка ошибок на e-mail
Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.
Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.
register_shutdown_function('error_alert');
function error_alert()
{
$error = error_get_last();
if (!empty($error)) {
mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true));
}
}
PHP
Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.
Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.
function error_alert($type, $message, $file, $line, $vars)
{
$error = array(
'type' => $type,
'message' => $message,
'file' => $file,
'line' => $line
);
error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
}
set_error_handler('error_alert');
PHP
4
Пользовательские ошибки
PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():
trigger_error('Пользовательская ошибка', E_USER_ERROR);
PHP
Результат:
Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
E_USER_ERROR– критическая ошибка,E_USER_WARNING– не критическая,E_USER_NOTICE– сообщения которые не являются ошибками,E_USER_DEPRECATED– сообщения о устаревшем коде.
10.10.2019, обновлено 09.10.2021
Другие публикации
Список основных кодов состояния HTTP, без WebDAV.
Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…
JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…
phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…
AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.
После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…
For syntax errors, you need to enable error display in the php.ini. By default these are turned off because you don’t want a «customer» seeing the error messages. Check this page in the PHP documentation for information on the 2 directives: error_reporting and display_errors. display_errors is probably the one you want to change. If you can’t modify the php.ini, you can also add the following lines to an .htaccess file:
php_flag display_errors on
php_value error_reporting 2039
You may want to consider using the value of E_ALL (as mentioned by Gumbo) for your version of PHP for error_reporting to get all of the errors. more info
3 other items: (1) You can check the error log file as it will have all of the errors (unless logging has been disabled). (2) Adding the following 2 lines will help you debug errors that are not syntax errors:
error_reporting(-1);
ini_set('display_errors', 'On');
(3) Another option is to use an editor that checks for errors when you type, such as PhpEd. PhpEd also comes with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.)
Cartman’s link is also very good: http://www.ibm.com/developerworks/library/os-debug/
Sumurai8
20k10 gold badges69 silver badges99 bronze badges
answered May 10, 2009 at 9:52
Darryl HeinDarryl Hein
141k91 gold badges216 silver badges260 bronze badges
3
![]()
Janyk
5713 silver badges18 bronze badges
answered Jul 4, 2011 at 19:46
EljakimEljakim
6,8572 gold badges16 silver badges16 bronze badges
6
The following code should display all errors:
<?php
// ----------------------------------------------------------------------------------------------------
// - Display Errors
// ----------------------------------------------------------------------------------------------------
ini_set('display_errors', 'On');
ini_set('html_errors', 0);
// ----------------------------------------------------------------------------------------------------
// - Error Reporting
// ----------------------------------------------------------------------------------------------------
error_reporting(-1);
// ----------------------------------------------------------------------------------------------------
// - Shutdown Handler
// ----------------------------------------------------------------------------------------------------
function ShutdownHandler()
{
if(@is_array($error = @error_get_last()))
{
return(@call_user_func_array('ErrorHandler', $error));
};
return(TRUE);
};
register_shutdown_function('ShutdownHandler');
// ----------------------------------------------------------------------------------------------------
// - Error Handler
// ----------------------------------------------------------------------------------------------------
function ErrorHandler($type, $message, $file, $line)
{
$_ERRORS = Array(
0x0001 => 'E_ERROR',
0x0002 => 'E_WARNING',
0x0004 => 'E_PARSE',
0x0008 => 'E_NOTICE',
0x0010 => 'E_CORE_ERROR',
0x0020 => 'E_CORE_WARNING',
0x0040 => 'E_COMPILE_ERROR',
0x0080 => 'E_COMPILE_WARNING',
0x0100 => 'E_USER_ERROR',
0x0200 => 'E_USER_WARNING',
0x0400 => 'E_USER_NOTICE',
0x0800 => 'E_STRICT',
0x1000 => 'E_RECOVERABLE_ERROR',
0x2000 => 'E_DEPRECATED',
0x4000 => 'E_USER_DEPRECATED'
);
if(!@is_string($name = @array_search($type, @array_flip($_ERRORS))))
{
$name = 'E_UNKNOWN';
};
return(print(@sprintf("%s Error in file xBB%sxAB at line %d: %sn", $name, @basename($file), $line, $message)));
};
$old_error_handler = set_error_handler("ErrorHandler");
// other php code
?>
The only way to generate a blank page with this code is when you have a error in the shutdown handler. I copied and pasted this from my own cms without testing it, but I am sure it works.
answered Aug 13, 2013 at 11:59
m4dm4x1337m4dm4x1337
1,8472 gold badges11 silver badges3 bronze badges
9
You can include the following lines in the file you want to debug:
error_reporting(E_ALL);
ini_set('display_errors', '1');
This overrides the default settings in php.ini, which just make PHP report the errors to the log.
answered May 10, 2009 at 9:54
TomalakTomalak
328k66 gold badges520 silver badges620 bronze badges
1
Errors and warnings usually appear in ....logsphp_error.log or ....logsapache_error.log depending on your php.ini settings.
Also useful errors are often directed to the browser, but as they are not valid html they are not displayed.
So "tail -f» your log files and when you get a blank screen use IEs «view» -> «source» menu options to view the raw output.
Jens
66.2k15 gold badges97 silver badges113 bronze badges
answered Sep 25, 2009 at 4:22
James AndersonJames Anderson
27k7 gold badges51 silver badges78 bronze badges
4
PHP Configuration
2 entries in php.ini dictate the output of errors:
display_errorserror_reporting
In production, display_errors is usually set to Off (Which is a good thing, because error display in production sites is generally not desirable!).
However, in development, it should be set to On, so that errors get displayed. Check!
error_reporting (as of PHP 5.3) is set by default to E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED (meaning, everything is shown except for notices, strict standards and deprecation notices). When in doubt, set it to E_ALL to display all the errors. Check!
Whoa whoa! No check! I can’t change my php.ini!
That’s a shame. Usually shared hosts do not allow the alteration of their php.ini file, and so, that option is sadly unavailable. But fear not! We have other options!
Runtime configuration
In the desired script, we can alter the php.ini entries in runtime! Meaning, it’ll run when the script runs! Sweet!
error_reporting(E_ALL);
ini_set("display_errors", "On");
These two lines will do the same effect as altering the php.ini entries as above! Awesome!
I still get a blank page/500 error!
That means that the script hadn’t even run! That usually happens when you have a syntax error!
With syntax errors, the script doesn’t even get to runtime. It fails at compile time, meaning that it’ll use the values in php.ini, which if you hadn’t changed, may not allow the display of errors.
Error logs
In addition, PHP by default logs errors. In shared hosting, it may be in a dedicated folder or on the same folder as the offending script.
If you have access to php.ini, you can find it under the error_log entry.
mario
143k20 gold badges236 silver badges288 bronze badges
answered Feb 2, 2014 at 20:47
![]()
Madara’s GhostMadara’s Ghost
170k50 gold badges264 silver badges308 bronze badges
1
I’m always using this syntax at the very top of the php script.
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
answered Sep 25, 2009 at 7:48
FDiskFDisk
8,0042 gold badges45 silver badges51 bronze badges
2
There is a really useful extension called «xdebug» that will make your reports much nicer as well.
answered May 10, 2009 at 9:59
gnarfgnarf
104k25 gold badges125 silver badges161 bronze badges
3
For quick, hands-on troubleshooting I normally suggest here on SO:
error_reporting(~0); ini_set('display_errors', 1);
to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in the php.ini and that you log the errors in PHP to catch syntax and startup errors.
The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.
Next things to consider:
- Install Xdebug and enable remote-debugging with your IDE.
See as well:
- Error Reporting (PHP The Right Way.)
- Predefined ConstantsDocs
error_reporting()Docsdisplay_errorsDocs
answered Jan 24, 2013 at 15:06
![]()
hakrehakre
189k51 gold badges425 silver badges823 bronze badges
It is possible to register an hook to make the last error or warning visible.
function shutdown(){
var_dump(error_get_last());
}
register_shutdown_function('shutdown');
adding this code to the beginning of you index.php will help you debug the problems.
answered Jan 5, 2016 at 18:59
1
If you are super cool, you might try:
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";
ini_set('display_errors',$test_server);
error_reporting(E_ALL|E_STRICT);
This will only display errors when you are running locally. It also gives you the test_server variable to use in other places where appropriate.
Any errors that happen before the script runs won’t be caught, but for 99% of errors that I make, that’s not an issue.
answered Jul 4, 2011 at 19:49
Rich BradshawRich Bradshaw
70.8k44 gold badges178 silver badges241 bronze badges
1
On the top of the page choose a parameter
error_reporting(E_ERROR | E_WARNING | E_PARSE);
answered May 6, 2013 at 14:14
KldKld
6,8533 gold badges36 silver badges50 bronze badges
This is a problem of loaded vs. runtime configuration
It’s important to recognize that a syntax error or parse error happens during the compile or parsing step, which means that PHP will bail before it’s even had a chance to execute any of your code. So if you are modifying PHP’s display_errors configuration during runtime, (this includes anything from using ini_set in your code to using .htaccess, which is a runtime configuration file) then only the default loaded configuration settings are in play.
How to always avoid WSOD in development
To avoid a WSOD you want to make sure that your loaded configuration file has display_errors on and error_reporting set to -1 (this is the equivalent E_ALL because it ensures all bits are turned on regardless of which version of PHP you’re running). Don’t hardcode the constant value of E_ALL, because that value is subject to change between different versions of PHP.
Loaded configuration is either your loaded php.ini file or your apache.conf or httpd.conf or virtualhost file. Those files are only read once during the startup stage (when you first start apache httpd or php-fpm, for example) and only overridden by runtime configuration changes. Making sure that display_errors = 1 and error_reporting = -1 in your loaded configuration file ensures that you will never see a WSOD regardless of syntax or parse error that occur before a runtime change like ini_set('display_errors', 1); or error_reporting(E_ALL); can take place.
How to find your (php.ini) loaded configuration files
To locate your loaded configuration file(s) just create a new PHP file with only the following code…
<?php
phpinfo();
Then point your browser there and look at Loaded Configuration File and Additional .ini files parsed, which are usually at the top of your phpinfo() and will include the absolute path to all your loaded configuration files.
If you see (none) instead of the file, that means you don’t have a php.ini in Configuration File (php.ini) Path. So you can download the stock php.ini bundled with PHP from here and copy that to your configuration file path as php.ini then make sure your php user has sufficient permissions to read from that file. You’ll need to restart httpd or php-fpm to load it in. Remember, this is the development php.ini file that comes bundled with the PHP source. So please don’t use it in production!
Just don’t do this in production
This really is the best way to avoid a WSOD in development. Anyone suggesting that you put ini_set('display_errors', 1); or error_reporting(E_ALL); at the top of your PHP script or using .htaccess like you did here, is not going to help you avoid a WSOD when a syntax or parse error occurs (like in your case here) if your loaded configuration file has display_errors turned off.
Many people (and stock installations of PHP) will use a production-ini file that has display_errors turned off by default, which typically results in this same frustration you’ve experienced here. Because PHP already has it turned off when it starts up, then encounters a syntax or parse error, and bails with nothing to output. You expect that your ini_set('display_errors',1); at the top of your PHP script should have avoided that, but it won’t matter if PHP can’t parse your code because it will never have reached the runtime.
answered Nov 12, 2015 at 6:24
![]()
SherifSherif
11.7k3 gold badges32 silver badges57 bronze badges
0
To persist this and make it confortale, you can edit your php.ini file. It is usually stored in /etc/php.ini or /etc/php/php.ini, but more local php.ini‘s may overwrite it, depending on your hosting provider’s setup guidelines. Check a phpinfo() file for Loaded Configuration File at the top, to be sure which one gets loaded last.
Search for display_errors in that file. There should be only 3 instances, of which 2 are commented.
Change the uncommented line to:
display_errors = stdout
sjas
18.1k12 gold badges85 silver badges91 bronze badges
answered Jul 4, 2011 at 19:54
![]()
RamRam
1,1611 gold badge10 silver badges34 bronze badges
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
answered Dec 4, 2017 at 20:54
Abuzer FirdousiAbuzer Firdousi
1,5541 gold badge10 silver badges25 bronze badges
I don’t know if it will help, but here is a piece of my standard config file for php projects. I tend not to depend too much on the apache configs even on my own server.
I never have the disappearing error problem, so perhaps something here will give you an idea.
Edited to show APPLICATON_LIVE
/*
APPLICATION_LIVE will be used in process to tell if we are in a development or production environment. It's generally set as early as possible (often the first code to run), before any config, url routing, etc.
*/
if ( preg_match( "%^(www.)?livedomain.com$%", $_SERVER["HTTP_HOST"]) ) {
define('APPLICATION_LIVE', true);
} elseif ( preg_match( "%^(www.)?devdomain.net$%", $_SERVER["HTTP_HOST"]) ) {
define('APPLICATION_LIVE', false);
} else {
die("INVALID HOST REQUEST (".$_SERVER["HTTP_HOST"].")");
// Log or take other appropriate action.
}
/*
--------------------------------------------------------------------
DEFAULT ERROR HANDLING
--------------------------------------------------------------------
Default error logging. Some of these may be changed later based on APPLICATION_LIVE.
*/
error_reporting(E_ALL & ~E_STRICT);
ini_set ( "display_errors", "0");
ini_set ( "display_startup_errors", "0");
ini_set ( "log_errors", 1);
ini_set ( "log_errors_max_len", 0);
ini_set ( "error_log", APPLICATION_ROOT."logs/php_error_log.txt");
ini_set ( "display_errors", "0");
ini_set ( "display_startup_errors", "0");
if ( ! APPLICATION_LIVE ) {
// A few changes to error handling for development.
// We will want errors to be visible during development.
ini_set ( "display_errors", "1");
ini_set ( "display_startup_errors", "1");
ini_set ( "html_errors", "1");
ini_set ( "docref_root", "http://www.php.net/");
ini_set ( "error_prepend_string", "<div style='color:red; font-family:verdana; border:1px solid red; padding:5px;'>");
ini_set ( "error_append_string", "</div>");
}
![]()
peterh
11.3k17 gold badges84 silver badges103 bronze badges
answered Sep 25, 2009 at 8:09
EliEli
96.3k20 gold badges75 silver badges81 bronze badges
2
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
ini_set('html_errors', 1);
In addition, you can get more detailed information with xdebug.
![]()
Janyk
5713 silver badges18 bronze badges
answered Aug 19, 2014 at 15:36
![]()
Yan.ZeroYan.Zero
4494 silver badges12 bronze badges
1
I recommend Nette Tracy for better visualization of errors and exceptions in PHP:

![]()
Janyk
5713 silver badges18 bronze badges
answered Jul 15, 2015 at 22:38
![]()
Ondřej ŠotekOndřej Šotek
1,7611 gold badge13 silver badges24 bronze badges
1
error_reporting(E_ALL | E_STRICT);
And turn on display errors in php.ini
answered May 10, 2009 at 9:54
![]()
Ólafur WaageÓlafur Waage
68k21 gold badges142 silver badges196 bronze badges
You can register your own error handler in PHP. Dumping all errors to a file might help you in these obscure cases, for example. Note that your function will get called, no matter what your current error_reporting is set to. Very basic example:
function dump_error_to_file($errno, $errstr) {
file_put_contents('/tmp/php-errors', date('Y-m-d H:i:s - ') . $errstr, FILE_APPEND);
}
set_error_handler('dump_error_to_file');
answered May 10, 2009 at 9:54
![]()
soulmergesoulmerge
72.6k19 gold badges118 silver badges153 bronze badges
0
The two key lines you need to get useful errors out of PHP are:
ini_set('display_errors',1);
error_reporting(E_ALL);
As pointed out by other contributors, these are switched off by default for security reasons. As a useful tip — when you’re setting up your site it’s handy to do a switch for your different environments so that these errors are ON by default in your local and development environments. This can be achieved with the following code (ideally in your index.php or config file so this is active from the start):
switch($_SERVER['SERVER_NAME'])
{
// local
case 'yourdomain.dev':
// dev
case 'dev.yourdomain.com':
ini_set('display_errors',1);
error_reporting(E_ALL);
break;
//live
case 'yourdomain.com':
//...
break;
}
Brad Larson♦
170k45 gold badges397 silver badges571 bronze badges
answered Jun 10, 2014 at 13:37
![]()
open your php.ini,
make sure it’s set to:
display_errors = On
restart your server.
![]()
Otiel
18.2k16 gold badges77 silver badges126 bronze badges
answered Jan 16, 2011 at 20:59
user577803user577803
611 silver badge1 bronze badge
0
You might also want to try PHPStorm as your code editor. It will find many PHP and other syntax errors right as you are typing in the editor.
answered Jun 18, 2014 at 1:03
if you are a ubuntu user then goto your terminal and run this command
sudo tail -50f /var/log/apache2/error.log
where it will display recent 50 errors.
There is a error file error.log for apache2 which logs all the errors.
Unihedron
10.8k13 gold badges60 silver badges70 bronze badges
answered Nov 10, 2014 at 11:23
![]()
To turn on full error reporting, add this to your script:
error_reporting(E_ALL);
This causes even minimal warnings to show up. And, just in case:
ini_set('display_errors', '1');
Will force the display of errors. This should be turned off in production servers, but not when you’re developing.
answered May 10, 2009 at 12:09
1
The “ERRORS” are the most useful things for the developers to know their mistakes and resolved them to make the system working perfect.
PHP provides some of better ways to know the developers why and where their piece of code is getting the errors, so by knowing those errors developers can make their code better in many ways.
Best ways to write following two lines on the top of script to get all errors messages:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Another way to use debugger tools like xdebug in your IDE.
![]()
Janyk
5713 silver badges18 bronze badges
answered Feb 1, 2014 at 6:24
In addition to all the wonderful answers here, I’d like to throw in a special mention for the MySQLi and PDO libraries.
In order to…
- Always see database related errors, and
- Avoid checking the return types for methods to see if something went wrong
The best option is to configure the libraries to throw exceptions.
MySQLi
Add this near the top of your script
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This is best placed before you use new mysqli() or mysqli_connect().
PDO
Set the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION on your connection instance. You can either do this in the constructor
$pdo = new PDO('driver:host=localhost;...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
or after creation
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
answered Sep 14, 2018 at 3:31
PhilPhil
152k23 gold badges235 silver badges236 bronze badges
You can enable full error reporting (including notices and strict messages). Some people find this too verbose, but it’s worth a try. Set error_reporting to E_ALL | E_STRICT in your php.ini.
error_reporting = E_ALL | E_STRICT
E_STRICT will notify you about deprecated functions and give you recommendations about the best methods to do certain tasks.
If you don’t want notices, but you find other message types helpful, try excluding notices:
error_reporting = (E_ALL | E_STRICT) & ~E_NOTICE
Also make sure that display_errors is enabled in php.ini. If your PHP version is older than 5.2.4, set it to On:
display_errors = "On"
If your version is 5.2.4 or newer, use:
display_errors = "stderr"
answered May 10, 2009 at 9:58
Ayman HouriehAyman Hourieh
129k22 gold badges143 silver badges116 bronze badges
Aside from error_reporting and the display_errors ini setting, you can get SYNTAX errors from your web server’s log files. When I’m developing PHP I load my development system’s web server logs into my editor. Whenever I test a page and get a blank screen, the log file goes stale and my editor asks if I want to reload it. When I do, I jump to the bottom and there is the syntax error. For example:
[Sun Apr 19 19:09:11 2009] [error] [client 127.0.0.1] PHP Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in D:\webroot\test\test.php on line 9
answered May 10, 2009 at 18:16
jmucchiellojmucchiello
18.5k7 gold badges41 silver badges61 bronze badges
This answer is brought to you by the department of redundancy department.
-
ini_set()/ php.ini / .htaccess / .user.iniThe settings
display_errorsanderror_reportinghave been covered sufficiently now. But just to recap when to use which option:ini_set()anderror_reporting()apply for runtime errors only.php.inishould primarily be edited for development setups. (Webserver and CLI version often have different php.ini’s).htaccessflags only work for dated setups (Find a new hoster! Well managed servers are cheaper.).user.iniare partial php.ini’s for modern setups (FCGI/FPM)
And as crude alternative for runtime errors you can often use:
set_error_handler("var_dump"); // ignores error_reporting and `@` suppression -
error_get_last()Can be used to retrieve the last runtime notice/warning/error, when error_display is disabled.
-
$php_errormsgIs a superlocal variable, which also contains the last PHP runtime message.
-
isset()begone!I know this will displease a lot of folks, but
issetandemptyshould not be used by newcomers. You can add the notice suppression after you verified your code is working. But never before.A lot of the «something doesn’t work» questions we get lately are the result of typos like:
if(isset($_POST['sumbit'])) # ↑↑You won’t get any useful notices if your code is littered with
isset/empty/array_keys_exists. It’s sometimes more sensible to use@, so notices and warnings go to the logs at least. -
assert_options(ASSERT_ACTIVE|ASSERT_WARNING);To get warnings for
assert()sections. (Pretty uncommon, but more proficient code might contain some.)PHP7 requires
zend.assertions=1in the php.ini as well. -
declare(strict_types=1);Bending PHP into a strictly typed language is not going to fix a whole lot of logic errors, but it’s definitely an option for debugging purposes.
-
PDO / MySQLi
And @Phil already mentioned PDO/MySQLi error reporting options. Similar options exist for other database APIs of course.
-
json_last_error()+json_last_error_msgFor JSON parsing.
-
preg_last_error()For regexen.
-
CURLOPT_VERBOSE
To debug curl requests, you need CURLOPT_VERBOSE at the very least.
-
shell/exec()Likewise will shell command execution not yield errors on its own. You always need
2>&1and peek at the $errno.
answered May 17, 2019 at 12:00
mariomario
143k20 gold badges236 silver badges288 bronze badges