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
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
Здравствуйте! Обычно для включения максимально подробного вывода ошибок я использую этот код:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
У меня вопрос. Чтобы отключить вывод ошибок вообще (если заливаю сайт на прод.), то нужен тот же самый код, только везде значения — 0? Или хватит только одной строчки? Если одной, то какая из них?
-
Вопрос задан
-
20025 просмотров
В точке входа в проект (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
Можно ли как-то запретить вывод предупреждений, которые по сути не являются критичными, в поток, т.е. чтобы в логи все писалось, но в поток ничего не шло.
Данная ситуация сильно напрягает при асинхронных запросах к серверу, когда вместо ожидаемого ответа от сервера на клиента возвращается текст предупреждения.
Понимаю, что это наверное неправильно, но все же.
-
Показать ещё
Загружается…
21 сент. 2023, в 19:28
10000 руб./за проект
21 сент. 2023, в 19:06
11111 руб./за проект
21 сент. 2023, в 19:00
6000000 руб./за проект
Минуточку внимания
In this guide, we will show you how to remove warning messages in PHP.
We will also explain why it is generally a bad idea to hide all warning messages.
Hiding all warning messages is basically the same as turning up the music in your car so that you can’t hear the worrying noise that your engine is making.
Hiding PHP warnings with the error_reporting function.
The error_reporting function allows us to tell PHP which errors to report.
For example, if we want to display all error messages except warnings, we can use the following line of code:
//Report all errors except warnings. error_reporting(E_ALL ^ E_WARNING);
Typically speaking, the error_reporting function should be placed at the top of your code. This is because the function can only control errors that occur in the code below it.
Can I hide PHP notice messages as well?
If you also want to hide notice messages, then you can set the following level in the error_reporting function:
//Only report fatal errors and parse errors. error_reporting(E_ERROR | E_PARSE); //This will usually create a division by 0 //warning message. echo 1 / 0; //This will usually create an array to string //notice message. echo array();
In the code snippet above, we told PHP that it should only report fatal errors (E_ERROR) and parse errors (E_PARSE).
Afterwards, we created two lines of code:
- We divided 1 by 0, which would typically result in a “Warning: Division by zero” message.
- We then attempted to echo out an array. Under normal circumstances, this would cause the following notice: “Notice: Array to string conversion”
If you run the example above, you will see that the page doesn’t display any notices or warnings. Furthermore, if you check the PHP error log, you will see that they also haven’t been logged.
Stopping warning messages from being displayed.
If you simply want to stop warning messages from being displayed, but not prevent them from being logged, then you can use the following piece of code:
//Tell PHP to log errors
ini_set('log_errors', 'On');
//Tell PHP to not display errors
ini_set('display_errors', 'Off');
//Set error_reporting to E_ALL
ini_set('error_reporting', E_ALL );
Here, we are using PHP’s ini_set function to dynamically modify the settings in our php.ini file:
- We set log_errors to On, which means that PHP will log warnings to our error log.
- We set display_errors to Off. As a result, PHP will not output errors to the screen.
- Finally, we set error_reporting to E_ALL.
Note: If you can access your php.ini file, then you should probably edit these values directly instead of changing them on the fly.
Using the @ character to suppress errors.
In some cases, you might not have control over certain warnings.
For example, a GET request to an external API could fail, resulting in a “failed to open stream” warning. To prevent this from occurring, we could use the @ character like so:
//API URL $url = 'http://example.com/api'; //Attempt to get contents of that URL $result = @file_get_contents($url);
As you can see, we have placed the @ (AT) character next to our function call. This means that if file_get_contents fails, it will not throw an E_WARNING message.
This works because the @ character is an error control operator that tells PHP to ignore any errors.
Note that error suppression should be used sparingly. Abusing this control operator can lead to issues that are difficult to debug.
Why should I not suppress all warning messages?
An E_WARNING message is an error that does not prevent the rest of your PHP script from executing. Although it does not halt the script, it is still an error. It means that something in your code is not working the way that it is supposed to be working.
You should always try to address the issue instead of hiding it. Otherwise, it may lead to other bugs further down the line.
If you sweep these warning messages under the rug, you will be limiting your ability to spot serious problems in your application.
For example, what if your online shop had a “division by one” error that was preventing certain users from adding multiple items to their basket? Perhaps this issue only occurs when the user applies an expired coupon. Or maybe it happens after they reduce the quantity of an item in their basket.
Either way, something bad is happening and you don’t know about it.
You cannot rely on end users to report issues. Many of them will either think that they are using the website incorrectly or they will simply forget about it and move on. Internet users are impatient. They usually won’t take the time to fill out contact forms or attach screenshots.
As a result, this lazy approach of “nuking” all warning messages has caused your online shop to lose out on sales.

