I have some PHP code. When I run it, a warning message appears.
How can I remove/suppress/ignore these warning messages?
asked Jan 1, 2010 at 0:32
1
You really should fix whatever’s causing the warning, but you can control visibility of errors with error_reporting()
. To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
Sean Bright
119k17 gold badges138 silver badges146 bronze badges
answered Jan 1, 2010 at 0:37
Tatu UlmanenTatu Ulmanen
123k34 gold badges187 silver badges185 bronze badges
4
You can put an @ in front of your function call to suppress all error messages.
@yourFunctionHere();
Mark Amery
144k81 gold badges406 silver badges459 bronze badges
answered Jan 1, 2010 at 0:41
PetPaulsenPetPaulsen
3,4422 gold badges22 silver badges33 bronze badges
12
To suppress warnings while leaving all other error reporting enabled:
error_reporting(E_ALL ^ E_WARNING);
Mark Amery
144k81 gold badges406 silver badges459 bronze badges
answered Feb 11, 2011 at 8:08
KarthikKarthik
1,4383 gold badges17 silver badges29 bronze badges
If you don’t want to show warnings as well as errors use
// Turn off all error reporting
error_reporting(0);
Error Reporting — PHP Manual
MD XF
7,8607 gold badges41 silver badges71 bronze badges
answered Jan 22, 2013 at 3:16
mohan.gademohan.gade
1,0951 gold badge9 silver badges15 bronze badges
0
If you want to suppress the warnings and some other error types (for example, notices) while displaying all other errors, you can do:
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
answered Jan 10, 2018 at 17:13
zstatezstate
1,9951 gold badge18 silver badges20 bronze badges
in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.
In WordPress hide Warnings and Notices add following code in wp-config.php file
ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
answered May 12, 2017 at 5:04
1
I do it as follows in my php.ini:
error_reporting = E_ALL & ~E_WARNING & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
This logs only fatal errors and no warnings.
honk
9,13711 gold badges75 silver badges83 bronze badges
answered Feb 27, 2018 at 8:43
navidnavid
1,0529 silver badges20 bronze badges
0
Not exactly answering the question, but I think this is a better compromise in some situations:
I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was — a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:
printf('<div style="display:none">');
...Third-party stuff here...
printf('</div>');
Warning was still in page source as a reminder to me, but invisible to the client.
FelixSFD
6,06210 gold badges43 silver badges117 bronze badges
answered Dec 30, 2012 at 20:03
DaveWalleyDaveWalley
81710 silver badges22 bronze badges
4
I think that better solution is configuration of .htaccess In that way you dont have to alter code of application. Here are directives for Apache2
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
answered May 10, 2014 at 16:34
You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.
Dharman♦
31.1k25 gold badges86 silver badges137 bronze badges
answered Jan 1, 2010 at 0:34
PekkaPekka
442k143 gold badges972 silver badges1089 bronze badges
1
There is already answer with Error Control Operator but it lacks of explanation. You can use @
operator with every expression and it hides errors (except of Fatal Errors).
@$test['test']; //PHP Notice: Undefined variable: test
@(14/0); // PHP Warning: Division by zero
//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error: Uncaught Error: Call to undefined function customFuntion()
For debugging it’s fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.
You should consider instead:
1. Error reporting settings as mentioned in accepted answer.
error_reporting(E_ERROR | E_PARSE);
or from PHP INI settings
ini_set('display_errors','Off');
2. Catching exceptions
try {
$var->method();
} catch (Error $e) {
// Handle error
echo $e->getMessage();
}
answered May 24, 2020 at 3:28
JsowaJsowa
9,1445 gold badges56 silver badges60 bronze badges
Здравствуйте! Обычно для включения максимально подробного вывода ошибок я использую этот код:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
У меня вопрос. Чтобы отключить вывод ошибок вообще (если заливаю сайт на прод.), то нужен тот же самый код, только везде значения — 0? Или хватит только одной строчки? Если одной, то какая из них?
-
Вопрос задан
-
20027 просмотров
В точке входа в проект (index.php), в самом начале выставить все по нулям
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);
Вывод ошибок лучше не выключать. Так вы лишите себя зацепок в случае багов на проде.
Для себя вывод подробностей ошибок перенаправляем в лог (файл/бд/другое хранилище).
Пользователю не нужно показывать подробности ошибок (стектрейс). Достаточно отобразить страницу с кратким описанием (понятным пользователю) ошибки, например «404 Не найдено то-то» или «500 Ошибка сервера».
Еще вариант — средиректить пользователя на главную страницу и флеш сообщением вывести краткое описание ошибки.
Я бы не рекомендовал затыкать вывод ошибок полностью, это bad practice. Пишу на PHP уже лет 10, и только недавно установил уровень E_ALL, исправление всех ошибок заняло где-то неделю, но сейчас я нарадоваться не могу, ибо ругается даже на отсутствие ключей в массиве (ибо в большинстве случаев если обращаются к какому-либо ключу, он должен быть в массиве, а его отсутствие — следствие какой-то проблемы). Об отсутствии какой-либо переменной я и вовсе не говорю. Для юзера достаточно просто подавить вывод ошибок (ибо сайт не будет работать только при E_FATAL и E_COMPILE, когда вообще не получается получить байткод), а для разрабов ошибки можно писать хоть в текстовый файл, используя собственный обработчик set_error_handler ().
Пригласить эксперта
Доступ к php.ini есть? Если да, то добавьтеdisplay_errors = off
Можно ли как-то запретить вывод предупреждений, которые по сути не являются критичными, в поток, т.е. чтобы в логи все писалось, но в поток ничего не шло.
Данная ситуация сильно напрягает при асинхронных запросах к серверу, когда вместо ожидаемого ответа от сервера на клиента возвращается текст предупреждения.
Понимаю, что это наверное неправильно, но все же.
-
Показать ещё
Загружается…
22 сент. 2023, в 01:22
10000 руб./за проект
22 сент. 2023, в 00:39
30000 руб./за проект
21 сент. 2023, в 22:23
5000 руб./за проект
Минуточку внимания
When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:
error_reporting(E_ERROR);
Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.
So you should first set it as verbose as possible with:
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
UPDATE: how to log errors instead of displaying them
As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.
A possible implementation is via the .htaccess file, useful if you don’t have access to the php.ini file (source).
# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
# Enable PHP error logging
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Prevent access to PHP error log
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
I have some PHP code. When I run it, a warning message appears.
How can I remove/suppress/ignore these warning messages?
asked Jan 1, 2010 at 0:32
1
You really should fix whatever’s causing the warning, but you can control visibility of errors with error_reporting()
. To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
Sean Bright
119k17 gold badges138 silver badges146 bronze badges
answered Jan 1, 2010 at 0:37
Tatu UlmanenTatu Ulmanen
123k34 gold badges187 silver badges185 bronze badges
4
You can put an @ in front of your function call to suppress all error messages.
@yourFunctionHere();
Mark Amery
144k81 gold badges406 silver badges459 bronze badges
answered Jan 1, 2010 at 0:41
PetPaulsenPetPaulsen
3,4422 gold badges22 silver badges33 bronze badges
12
To suppress warnings while leaving all other error reporting enabled:
error_reporting(E_ALL ^ E_WARNING);
Mark Amery
144k81 gold badges406 silver badges459 bronze badges
answered Feb 11, 2011 at 8:08
KarthikKarthik
1,4383 gold badges17 silver badges29 bronze badges
If you don’t want to show warnings as well as errors use
// Turn off all error reporting
error_reporting(0);
Error Reporting — PHP Manual
MD XF
7,8607 gold badges41 silver badges71 bronze badges
answered Jan 22, 2013 at 3:16
mohan.gademohan.gade
1,0951 gold badge9 silver badges15 bronze badges
0
If you want to suppress the warnings and some other error types (for example, notices) while displaying all other errors, you can do:
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
answered Jan 10, 2018 at 17:13
zstatezstate
1,9951 gold badge18 silver badges20 bronze badges
in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.
In WordPress hide Warnings and Notices add following code in wp-config.php file
ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
answered May 12, 2017 at 5:04
1
I do it as follows in my php.ini:
error_reporting = E_ALL & ~E_WARNING & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
This logs only fatal errors and no warnings.
honk
9,13711 gold badges75 silver badges83 bronze badges
answered Feb 27, 2018 at 8:43
navidnavid
1,0529 silver badges20 bronze badges
0
Not exactly answering the question, but I think this is a better compromise in some situations:
I had a warning message as a result of a printf() statement in a third-party library. I knew exactly what the cause was — a temporary work-around while the third-party fixed their code. I agree that warnings should not be suppressed, but I could not demonstrate my work to a client with the warning message popping up on screen. My solution:
printf('<div style="display:none">');
...Third-party stuff here...
printf('</div>');
Warning was still in page source as a reminder to me, but invisible to the client.
FelixSFD
6,06210 gold badges43 silver badges117 bronze badges
answered Dec 30, 2012 at 20:03
DaveWalleyDaveWalley
81710 silver badges22 bronze badges
4
I think that better solution is configuration of .htaccess In that way you dont have to alter code of application. Here are directives for Apache2
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
answered May 10, 2014 at 16:34
You could suppress the warning using error_reporting but the much better way is to fix your script in the first place.
Dharman♦
31.1k25 gold badges86 silver badges137 bronze badges
answered Jan 1, 2010 at 0:34
PekkaPekka
442k143 gold badges972 silver badges1089 bronze badges
1
There is already answer with Error Control Operator but it lacks of explanation. You can use @
operator with every expression and it hides errors (except of Fatal Errors).
@$test['test']; //PHP Notice: Undefined variable: test
@(14/0); // PHP Warning: Division by zero
//This is not working. You can't hide Fatal Errors this way.
@customFuntion(); // PHP Fatal error: Uncaught Error: Call to undefined function customFuntion()
For debugging it’s fast and perfect method. But you should never ever use it on production nor permanent include in your local version. It will give you a lot of unnecessary irritation.
You should consider instead:
1. Error reporting settings as mentioned in accepted answer.
error_reporting(E_ERROR | E_PARSE);
or from PHP INI settings
ini_set('display_errors','Off');
2. Catching exceptions
try {
$var->method();
} catch (Error $e) {
// Handle error
echo $e->getMessage();
}
answered May 24, 2020 at 3:28
JsowaJsowa
9,1445 gold badges56 silver badges60 bronze badges
От автора: за свои ошибки нужно отвечать! Их нужно исправлять! Но ведь можно исправить как-нибудь потом, когда будет время? В настоящей жизни такое не всегда возможно, а на своем сайте для этого нужно лишь в PHP отключить ошибки.
Зачем прятать свои программные «недостатки»?
Тут, однако, «попахивает» философией, господа разработчики! А программирование и философия – это далеко идущие друг от друга дисциплины. Понятно, что если скрыть свои баги в коде, тогда будет не так стыдно. И никто не узнает, что вы только начинающий программист :).
В программировании желание убрать ошибки PHP не всегда говорит о непорядочности веб-разработчика. А скорее наоборот: таким образом он пытается обезопасить систему работающего ресурса от взлома и «не напрягать» пользователей отображением сообщений о существующих «недугах» в коде сайта.
Вывод ошибок приветствуется и востребован только на этапе «зарождения» нового ресурса. При его создании каждый из модулей движка должен пройти скрупулезную стадию тестирования. И все для того, чтобы затем корректно работать в составе всей системы.
С помощью сообщений, выдаваемых ядром языка, разработчик узнает о существующей проблеме. Дополнительно каждое уведомление об ошибке сопровождается коротким пояснением характера ее происхождения. Что позволяет разработчику как можно быстрее исправить допущенный «прокол».
Отображение системных сообщений не только портит впечатление пользователей о ресурсе, но и делает его крайне уязвимым. Вот почему так важно отключать показ ошибок в PHP на работающем сайте.
Пример уязвимости
На следующем примере я попытаюсь доказать вам, что афишировать свои программные ошибки не всегда безопасно. Предположим, что сайт работает на каком-то движке, написанном с помощью MySQL и PHP. В одном из скриптов невыспавшийся кодер неправильно прописал пароль в строке подключения.
После запуска скрипта на сайте все пользователи увидят на экране описание данной ошибки. А хакер – получит логин пользователя без всякого взлома, «шума и пыли». Гляньте на следующий скриншот:
Закрываем дыру
В коде такую серьезную прореху можно «закрыть» с помощью «собаки». Точнее, символа «@». Пример:
@$load= mysqli_connect(‘localhost’, ‘root’, ‘321’, ‘site’); |
Или с помощью функции error_reporting(), передав ей в качестве значения 0.
В первом варианте (с «собачкой») мы отключаем отображение ошибки, допущенной в одной строке. Во втором – запрещаем вывод уведомлений для всего кода скрипта.
Через файлы конфигурации
Кроме этого отключить ошибки PHP можно в htaccess. Данный файл содержит в себе настройки веб-сервера Apache. Чтобы системные сообщения о «багах» не появлялись на страницах ресурса, в данный фал следует добавить следующие строчки:
php_flag display_errors on php_value error_reporting 0 |
Получается, что таким образом мы воздействуем не на отдельно взятый скрипт, а на весь код движка в целом. Но это не единственный способ глобального воздействия. Если вы используете Денвер, тогда в нем язык программирования работает в режиме шлюза (CGI). В таком случае нужно отключать ошибки в PHP ini. Найдите в данном файле следующую строку и измените значение директивы на off.
Ну, вроде разобрались, как и когда в PHP нужно «отключать» свою совесть и запрещать отображение сообщений об ошибках. Причем в некоторых случаях это не только можно делать, но и нужно.