Error reporting php none

(PHP 4, PHP 5, PHP 7, PHP 8)

(PHP 4, PHP 5, PHP 7, PHP 8)

error_reportingSets which PHP errors are reported

Description

error_reporting(?int $error_level = null): int

Parameters

error_level

The new error_reporting
level. It takes on either a bitmask, or named constants. Using named
constants is strongly encouraged to ensure compatibility for future
versions. As error levels are added, the range of integers increases,
so older integer-based error levels will not always behave as expected.

The available error level constants and the actual
meanings of these error levels are described in the
predefined constants.

Return Values

Returns the old error_reporting
level or the current level if no error_level parameter is
given.

Changelog

Version Description
8.0.0 error_level is nullable now.

Examples

Example #1 error_reporting() examples


<?php// Turn off all error reporting
error_reporting(0);// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);// Report all PHP errors
error_reporting(E_ALL);// Report all PHP errors
error_reporting(-1);// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>

Notes

Tip

Passing in the value -1 will show every possible error,
even when new levels and constants are added in future PHP versions. The
behavior is equivalent to passing E_ALL constant.

See Also

  • The display_errors directive
  • The html_errors directive
  • The xmlrpc_errors directive
  • ini_set() — Sets the value of a configuration option

info at hephoz dot de

14 years ago


If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:

- create a new file in which you include the faulty script:

<?php
error_reporting
(E_ALL);
ini_set("display_errors", 1);
include(
"file_with_errors.php");
?>

- execute this file instead of the faulty script file

now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!


dave at davidhbrown dot us

16 years ago


The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.

If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:

<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>

^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.


jcastromail at yahoo dot es

2 years ago


Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character. 

For example

<?php

$a

=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8?>


Fernando Piancastelli

18 years ago


The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set

display_errors = On
error_reporting = ~E_ALL

to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.


lhenry at lhenry dot com

3 years ago


In php7,  what was generally a notice or a deprecated is now a warning : the same level of a mysql error …  unacceptable for me.

I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.

So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING

Custom overriding the level of php errors should be super handy and flexible …


ecervetti at orupaca dot fr

13 years ago


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

luisdev

4 years ago


This article refers to these two reporting levels:

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

What is the difference between those two levels?

Please update this article with a clear explanation of the difference and the possible use cases.


qeremy ! gmail

7 years ago


If you want to see all errors in your local environment, you can set your project URL like "foo.com.local" locally and put that in bootstrap file.

<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
   
ini_set('display_errors', 1);
   
ini_set('error_reporting', E_ALL);
   
// or error_reporting(E_ALL);
}
?>


Rash

8 years ago


If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.

So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.


chris at ocproducts dot com

6 years ago


The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).

keithm at aoeex dot com

12 years ago


Some E_STRICT errors seem to be thrown during the page's compilation process.  This means they cannot be disabled by dynamically altering the error level at run time within that page.

The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.

Ex, rename index.php to index.inc.php, then re-create index.php as:

<?php
error_reporting
(E_ALL & ~(E_STRICT|E_NOTICE));
require(
'index.inc.php');
?>

That allows you to alter the error reporting prior to the file being compiled.

I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.


kevinson112 at yahoo dot com

4 years ago


I had the problem that if there was an error, php would just give me a blank page.  Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc.  But simply running the file in a different directory allowed it to show errors!

Turns out that the error_log file in the one directory was full (2.0 Gb).  I erased the file and now errors are displayed normally.  It might also help to turn error logging off.

https://techysupport.co/norton-tech-support/


adam at adamhahn dot com

5 years ago


To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.

<?php
error_reporting
(E_ALL);
var_dump(
   
error_reporting(), // value of E_ALL,
   
@error_reporting() // value is 0
);
?>


vdephily at bluemetrix dot com

17 years ago


Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting
(E_ALL);$foo = $bar; //notice : $bar uninitialized$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok$foo = $bar['nope'] // notice : no such index
?>

fredrik at demomusic dot nu

17 years ago


Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".

This is very useful to remember when setting error_reporting levels in httpd.conf:

Use the table above or:

<?php

ini_set
("error_reporting", E_YOUR_ERROR_LEVEL);

echo
ini_get("error_reporting");

?>



To get the appropriate integer for your error-level. Then use:

php_admin_value error_reporting YOUR_INT

in httpd.conf

I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...

Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?


rojaro at gmail dot com

12 years ago


To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

<?php error_reporting(-1); ?>


j dot schriver at vindiou dot com

22 years ago


error_reporting() has no effect if you have defined your own error handler with set_error_handler()

[Editor's Note: This is not quite accurate.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.

All other levels of errors will be passed to the custom error handler defined by set_error_handler().

Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:

if (!($type & error_reporting())) return;

-zak@php.net]


kc8yds at gmail dot com

14 years ago


this is to show all errors for code that may be run on different versions

for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL

if anyone sees any problems with it please correct this post

<?php

ini_set
('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);

?>


misplacedme at gmail dot com

13 years ago


I always code with E_ALL set.
After a couple of pages of
<?php
$username
= (isset($_POST['username']) && !empty($_POST['username']))....
?>

I made this function to make things a little bit quicker.  Unset values passed by reference won't trigger a notice.

<?php
function test_ref(&$var,$test_function='',$negate=false) {
   
$stat = true;
    if(!isset(
$var)) $stat = false;
    if (!empty(
$test_function) && function_exists($test_function)){
       
$stat = $test_function($var);
       
$stat = ($negate) ? $stat^1 : $stat;
    }
    elseif(
$test_function == 'empty') {
       
$stat = empty($var);
       
$stat = ($negate) ? $stat^1 : $stat;
    }
    elseif (!
function_exists($test_function)) {
       
$stat = false;
       
trigger_error("$test_function() is not a valid function");
    }
   
$stat = ($stat) ? true : false;
    return
$stat;
}
$a = '';
$b = '15';test_ref($a,'empty',true);  //False
test_ref($a,'is_int');  //False
test_ref($a,'is_numeric');  //False
test_ref($b,'empty',true);  //true
test_ref($b,'is_int');  //False
test_ref($b,'is_numeric');  //false
test_ref($unset,'is_numeric');  //false
test_ref($b,'is_number');  //returns false, with an error.
?>


Alex

16 years ago


error_reporting() may give unexpected results if the @ error suppression directive is used.

<?php
@include 'config.php';
include
'foo.bar';        // non-existent file
?>

config.php
<?php
error_reporting
(0);
?>

will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings).  If the suppressor is removed, this works as expected.

Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result.  This is contrary to the note above which says that the two instructions are equivalent.


teynon1 at gmail dot com

10 years ago


It might be a good idea to include E_COMPILE_ERROR in error_reporting.

If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.

Example:
<?php
  error_reporting
(E_ERROR | E_WARNING | E_PARSE);

  function

myErrorHandler($errno, $errstr, $errfile, $errline) {
   
// Do something other than output message.
   
return true;
  }
$old_error_handler = set_error_handler("myErrorHandler");

  require

"this file does not exist";
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

<?php
  error_reporting
(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>


Daz Williams (The Northeast)

13 years ago


Only display php errors to the developer...

<?php

if($_SERVER['REMOTE_ADDR']=="00.00.00.00")

{

 
ini_set('display_errors','On');

}

else

{

 
ini_set('display_errors','Off');

}

?>



Just replace 00.00.00.00 with your ip address.


forcemdt

9 years ago


Php >5.4

Creating a Custom Error Handler

set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
  }


huhiko334 at yandex dot ru

4 years ago


If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct

DarkGool

17 years ago


In phpinfo() error reporting level display like a bit (such as 4095)

Maybe it is a simply method to understand what a level set on your host

if you are not have access to php.ini file

<?php

$bit
= ini_get('error_reporting');

while (
$bit > 0) {

    for(
$i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {

       
$end = $i;

    }

   
$res[] = $end;

   
$bit = $bit - $end;

}

?>



In $res you will have all constants of error reporting

$res[]=int(16) // E_CORE_ERROR

$res[]=int(8)    // E_NOTICE

...


&IT

2 years ago


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

error_reporting

(PHP 4, PHP 5, PHP 7)

error_reporting
Задает, какие ошибки PHP попадут в отчет

Описание

int error_reporting
([ int $level
] )

Список параметров

level

Новое значение уровня
error_reporting. Это может
быть битовая маска или именованные константы. При использовании
именованных констант нужно будет следить за совместимостью с новыми
версиями PHP. В новых версиях могут добавиться новые уровни ошибок,
увеличиться диапазон целочисленных типов. Все это может привести к
нестабильной работе при использовании старых целочисленных обозначений
уровней ошибок.

Доступные константы уровней ошибок и их описания приведены в разделе
Предопределенные константы.

Возвращаемые значения

Возвращает старое значение уровня
error_reporting либо текущее
значение, если аргумент level не задан.

Список изменений

Версия Описание
5.4.0 E_STRICT стал частью
E_ALL.
5.3.0 Добавлены E_DEPRECATED и
E_USER_DEPRECATED.
5.2.0 Добавлена E_RECOVERABLE_ERROR.
5.0.0 Добавлена E_STRICT (не входит в состав
E_ALL).

Примеры

Пример #1 Примеры использования error_reporting()


<?php// Выключение протоколирования ошибок
error_reporting(0);// Включать в отчет простые описания ошибок
error_reporting(E_ERROR E_WARNING E_PARSE);// Включать в отчет E_NOTICE сообщения (добавятся сообщения о 
//непроинициализированных переменных или ошибках в именах переменных)
error_reporting(E_ERROR E_WARNING E_PARSE E_NOTICE);// Добавлять сообщения обо всех ошибках, кроме E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);// Добавлять в отчет все PHP ошибки (см. список изменений)
error_reporting(E_ALL);// Добавлять в отчет все PHP ошибки
error_reporting(-1);// То же, что и error_reporting(E_ALL);
ini_set('error_reporting'E_ALL);?>

Примечания

Внимание

Большинство E_STRICT ошибок отлавливаются на этапе
компиляции, поэтому такие ошибки не включаются в отчет в файлах, где
error_reporting расширен для
включения E_STRICT ошибок (и наоборот).

Подсказка

Если передать -1, будут отображаться все возможные
ошибки, даже если в новых версиях PHP добавятся уровни или константы. В
версии PHP 5.4. передача константы E_ALL дает
тот же результат.

Вернуться к: Функции обработки ошибок

I am trying to turn off all errors on my website. I have followed different tutorials on how to do this, but I keep getting read and open error messages. Is there something I am missing?

I have tried the following in my php.ini file:

;Error display
display_startup_errors = Off
display_errors = Off
html_errors = Off
docref_root = 0
docref_ext = 0

For some reason when I do a fileopen() call for a file which does not exist, I still get the error displayed. This is not safe for a live website, for obvious reasons.

Peter Mortensen's user avatar

asked Apr 11, 2013 at 12:52

Jms Bnd's user avatar

3

I always use something like this in a configuration file:

// Toggle this to change the setting
define('DEBUG', true);

// You want all errors to be triggered
error_reporting(E_ALL);

if(DEBUG == true)
{
    // You're developing, so you want all errors to be shown
    display_errors(true);

    // Logging is usually overkill during development
    log_errors(false);
}
else
{
    // You don't want to display errors on a production environment
    display_errors(false);

    // You definitely want to log any occurring
    log_errors(true);
}

This allows easy toggling between debug settings. You can improve this further by checking on which server the code is running (development, test, acceptance, and production) and change your settings accordingly.

Note that no errors will be logged if error_reporting is set to 0, as cleverly remarked by Korri.

Peter Mortensen's user avatar

answered Apr 11, 2013 at 12:59

Sherlock's user avatar

SherlockSherlock

7,4776 gold badges36 silver badges79 bronze badges

4

You should consider not displaying your error messages instead!

Set ini_set('display_errors', 'Off'); in your PHP code (or directly into your ini file if possible), and leave error_reporting on E_ALL or whatever kind of messages you would like to find in your logs.

This way you can handle errors later, while your users still don’t see them.

Full example:

define('DEBUG', true);
error_reporting(E_ALL);

if (DEBUG)
{
    ini_set('display_errors', 'On');
}
else
{
    ini_set('display_errors', 'Off');
}

Or simply (same effect):

define('DEBUG', true);

error_reporting(E_ALL);
ini_set('display_errors', DEBUG ? 'On' : 'Off');

Peter Mortensen's user avatar

answered Feb 11, 2014 at 10:52

Levite's user avatar

LeviteLevite

16.9k8 gold badges50 silver badges50 bronze badges

2

In php.ini, comment out:

error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE

By placing a ; ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE)

For disabling in a single file, place error_reporting(0); after opening a php tag.

Peter Mortensen's user avatar

answered Apr 11, 2013 at 13:01

Vishnu R's user avatar

Vishnu RVishnu R

1,8593 gold badges26 silver badges45 bronze badges

1

In file php.ini you should try this for all errors:

error_reporting = off

Urs's user avatar

Urs

4,8947 gold badges51 silver badges115 bronze badges

answered Apr 1, 2014 at 15:45

Shahzeb chohan's user avatar

1

Let me quickly summarize this for reference:

  • error_reporting() adapts the currently active setting for the default error handler.

  • Editing the error reporting ini options also changes the defaults.

    • Here it’s imperative to edit the correct php.ini version — it’s typically /etc/php5/fpm/php.ini on modern servers, /etc/php5/mod_php/php.ini alternatively; while the CLI version has a distinct one.

    • Alternatively you can use depending on SAPI:

      • mod_php: .htaccess with php_flag options
      • FastCGI: commonly a local php.ini
      • And with PHP above 5.3 also a .user.ini
    • Restarting the webserver as usual.

If your code is unwieldy and somehow resets these options elsewhere at runtime, then an alternative and quick way is to define a custom error handler that just slurps all notices/warnings/errors up:

set_error_handler(function(){});

Again, this is not advisable, just an alternative.

answered Jul 30, 2014 at 1:16

mario's user avatar

mariomario

143k20 gold badges236 silver badges288 bronze badges

2

In file php.ini you should try this for all errors:

display_errors = On

Location file is:

  • Ubuntu 16.04:/etc/php/7.0/apache2
  • CentOS 7:/etc/php.ini

answered Mar 10, 2015 at 4:26

1

You can also use PHP’s error_reporting();

// Disable it all for current call
error_reporting(0);

If you want to ignore errors from one function only, you can prepend a @ symbol.

@any_function(); // Errors are ignored

Peter Mortensen's user avatar

answered Apr 11, 2013 at 12:54

Tim S.'s user avatar

Tim S.Tim S.

13.4k7 gold badges43 silver badges72 bronze badges

1

I usually use PHP’s built in error handlers that can handle every possible error outside of syntax and still render a nice ‘Down for maintenance’ page otherwise:

Format PHP error on production server

Peter Mortensen's user avatar

answered Mar 10, 2015 at 4:33

Vladimir Ramik's user avatar

Vladimir RamikVladimir Ramik

1,9202 gold badges12 silver badges23 bronze badges

Open your php.ini file (If you are using Linux — sudo vim /etc/php5/apache2/php.ini)

Add this lines into that file

   error_reporting = E_ALL & ~E_WARNING 

(If you need to disabled any other errors -> error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING)

    display_errors = On

And finally you need to restart your APACHE server.

answered Jan 5, 2016 at 9:26

UWU_SANDUN's user avatar

UWU_SANDUNUWU_SANDUN

1,10513 silver badges19 bronze badges

It is not enough in case of PHP fpm. It was one more configuration file which can enable display_error. You should find www.conf. In my case it is in directory /etc/php/7.1/fpm/pool.d/

You should find php_flag[display_errors] = on and disable it, php_flag[display_errors] = off. This should solve the issue.

Peter Mortensen's user avatar

answered Jan 25, 2019 at 16:55

Vazgen Manukyan's user avatar

Vazgen ManukyanVazgen Manukyan

1,3801 gold badge11 silver badges17 bronze badges

It’s been quite some time and iam sure OP’s answer is cleared. If any new user still looking for answer and scrolled this far, then here it is.

Check your updated information in php.ini file

Using Windows explorer:

C/xampp/php/php.ini

Using XAMPP Control Panel

  1. Click the Config button for ‘Apache’ (Stop | Admin | Config | Logs)
  2. Select PHP (php.ini)

Can i create my own phpinfo()? Yes you can

  1. Create a phpinfo.php in your root directly or anywhere you want
  2. Place this <?php phpinfo(); ?>
  3. Save the file.
  4. Open the file and you should see all the details.

How to set display_errors to Off in my own file without using php.ini

You can do this using ini_set() function. Read more about ini_set() here (https://www.php.net/manual/en/function.ini-set.php)

  1. Go to your header.php or index.php
  2. add this code ini_set('display_errors', FALSE);

To check the output without accessing php.ini file

$displayErrors = (ini_get('display_errors') == 1) ? 'On' : 'Off';
$PHPCore = array(
    'Display error' => $displayErrors
    // add other details for more output
);
foreach ($PHPCore as $key => $value) {
    echo "$key: $value";
}

answered Jul 30, 2020 at 23:50

Dexter's user avatar

DexterDexter

7,2553 gold badges37 silver badges36 bronze badges

Настройка во время выполнения

Поведение этих функций зависит от установок в php.ini.

Настройки конфигурации протоколирования событий и ошибок

Имя По умолчанию Место изменения Список изменений
error_reporting NULL PHP_INI_ALL  
display_errors «1» PHP_INI_ALL  
display_startup_errors «1» PHP_INI_ALL До PHP 8.0.0 значение по умолчанию было "0".
log_errors «0» PHP_INI_ALL  
log_errors_max_len «1024» PHP_INI_ALL  
ignore_repeated_errors «0» PHP_INI_ALL  
ignore_repeated_source «0» PHP_INI_ALL  
report_memleaks «1» PHP_INI_ALL  
track_errors «0» PHP_INI_ALL Объявлено устаревшим в PHP 7.2.0, удалено в PHP 8.0.0.
html_errors «1» PHP_INI_ALL  
xmlrpc_errors «0» PHP_INI_SYSTEM  
xmlrpc_error_number «0» PHP_INI_ALL  
docref_root «» PHP_INI_ALL  
docref_ext «» PHP_INI_ALL  
error_prepend_string NULL PHP_INI_ALL  
error_append_string NULL PHP_INI_ALL  
error_log NULL PHP_INI_ALL  
error_log_mode 0o644 PHP_INI_ALL Доступно, начиная с PHP 8.2.0
syslog.facility «LOG_USER» PHP_INI_SYSTEM Доступно, начиная с PHP 7.3.0.
syslog.filter «no-ctrl» PHP_INI_ALL Доступно, начиная с PHP 7.3.0.
syslog.ident «php» PHP_INI_SYSTEM Доступно, начиная с PHP 7.3.0.

Для подробного описания констант
PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.

Краткое разъяснение конфигурационных
директив.

error_reporting
int

Задаёт уровень протоколирования ошибки. Параметр может быть либо числом,
представляющим битовое поле, либо именованной константой.
Соответствующие уровни и константы приведены в разделе
Предопределённые константы,
а также в php.ini. Для установки настройки во время выполнения используйте функцию
error_reporting(). Смотрите также описание директивы
display_errors.

Значение по умолчанию равно E_ALL.

До PHP 8.0.0 значение по умолчанию было:
E_ALL &
~E_NOTICE &
~E_STRICT &
~E_DEPRECATED
.
При этой настройке не отображаются уровни ошибок E_NOTICE,
E_STRICT и E_DEPRECATED.

Замечание:
PHP-константы за пределами PHP

Использование PHP-констант за пределами PHP, например в файле
httpd.conf, не имеет смысла, так как в таких случаях требуются
целочисленные значения (int). Более того, с течением времени будут
добавляться новые уровни ошибок, а максимальное значение константы
E_ALL соответственно будет расти. Поэтому в месте, где
предполагается указать E_ALL, лучше задать большое целое число,
чтобы перекрыть все возможные битовые поля. Таким числом может быть, например,
2147483647 (оно включит все возможные ошибки, не
только E_ALL).

display_errors
string

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

Значение "stderr" посылает ошибки в поток stderr
вместо stdout.

Замечание:

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

Замечание:

Несмотря на то, что display_errors может быть установлена во время выполнения
(функцией ini_set()), это ни на что не повлияет, если в скрипте есть
фатальные ошибки. Это обусловлено тем, что ожидаемые действия программы во время
выполнения не получат управления (не будут выполняться).

display_startup_errors
bool

Даже если display_errors включена, ошибки, возникающие во время запуска PHP, не будут
отображаться. Настойчиво рекомендуем включать директиву display_startup_errors только
для отладки.

log_errors
bool

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

Замечание:

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

log_errors_max_len
int

Задание максимальной длины log_errors в байтах. В
error_log добавляется информация
об источнике. Значение по умолчанию 1024. Установка значения в 0
позволяет снять ограничение на длину log_errors. Это ограничение
распространяется на записываемые в журнал ошибки, на отображаемые ошибки,
а также на $php_errormsg, но не на явно вызываемые функции,
такие как error_log().

Если используется int, значение измеряется байтами. Вы также можете использовать сокращённую запись, которая описана в этом разделе FAQ.

ignore_repeated_errors
bool

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

ignore_repeated_source
bool

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

report_memleaks
bool

Если настройка включена (по умолчанию), будет формироваться отчёт об утечках памяти,
зафиксированных менеджером памяти Zend. На POSIX платформах этот отчёт будет
направляться в поток stderr. На Windows платформах он будет посылаться в отладчик
функцией OutputDebugString(), просмотреть отчёт в этом случае можно с помощью утилит,
вроде » DbgView. Эта настройка имеет
смысл в сборках, предназначенных для отладки. При этом
E_WARNING должна быть включена в список error_reporting.

track_errors
bool

Если включена, последняя произошедшая ошибка будет первой в переменной
$php_errormsg.

html_errors
bool

Если разрешена, сообщения об ошибках будут включать теги HTML. Формат для
HTML-ошибок производит нажимаемые ссылки, ведущие на описание ошибки, либо
функии, в которой она произошла. За такие ссылки ответственны
docref_root и
docref_ext.

Если запрещена, то ошибки будут выдаваться простым текстом, без форматирования.

xmlrpc_errors
bool

Если включена, то нормальное оповещение об ошибках отключается и, вместо него,
ошибки выводятся в формате XML-RPC.

xmlrpc_error_number
int

Используется в качестве значения XML-RPC элемента faultCode.

docref_root
string

Новый формат ошибок содержит ссылку на страницу с описанием ошибки или
функции, вызвавшей эту ошибку. Можно разместить копию
описаний ошибок и функций локально и задать ini директиве значение
URL этой копии. Если, например, локальная копия описаний доступна по
адресу "/manual/", достаточно прописать
docref_root=/manual/. Дополнительно, необходимо
задать значение директиве docref_ext, отвечающей за соответствие
расширений файлов файлам описаний вашей локальной копии,
docref_ext=.html. Также возможно использование
внешних ссылок. Например,
docref_root=http://manual/en/ или
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"

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

Замечание:

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

docref_ext
string

Смотрите docref_root.

Замечание:

Значение docref_ext должно начинаться с точки ".".

error_prepend_string
string

Строка, которая будет выводиться непосредственно перед сообщением об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке.

error_append_string
string

Строка, которая будет выводиться после сообщения об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке.

error_log
string

Имя файла, в который будут добавляться сообщения об ошибках. Файл
должен быть открыт для записи пользователем веб-сервера. Если
используется специальное значение syslog, то
сообщения будут посылаться в системный журнал. На Unix-системах это
syslog(3), на Windows NT — журнал событий. Смотрите также: syslog().
Если директива не задана, ошибки будут направляться в SAPI журналы.
Например, это могут быть журналы ошибок Apache или поток
stderr командной строки CLI.
Смотрите также функцию error_log().

error_log_mode
int

Режим файла, описанного в error_log.

syslog.facility
string

Указывает, какой тип программы регистрирует сообщение.
Действует только в том случае, если опция error_log установлена в «syslog».

syslog.filter
string

Указывает тип фильтра для фильтрации регистрируемых сообщений.
Разрешённые символы передаются без изменений; все остальные записываются в шестнадцатеричном представлении с префиксом x.

  • all – строка будет разделена
    на символы новой строки и все символы будут переданы без изменений
  • ascii – строка будет разделена
    на символы новой строки, а любые непечатаемые 7-битные символы ASCII будут экранированы
  • no-ctrl – строка будет разделена
    на символы новой строки, а любые непечатаемые символы будут экранированы
  • raw – все символы передаются в системный
    журнал без изменений, без разделения на новые строки (идентично PHP до 7.3)

Параметр влияет на ведение журнала через error_log установленного в «syslog» и вызовы syslog().

Замечание:

Тип фильтра raw доступен начиная с PHP 7.3.8 и PHP 7.4.0.


Директива не поддерживается в Windows.

syslog.ident
string

Определяет строку идентификатора, которая добавляется к каждому сообщению.
Действует только в том случае, если опция error_log установлена в «syslog».

cjakeman at bcs dot org

13 years ago


Using

<?php ini_set('display_errors', 1); ?>

at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.

This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set

display_errors On

then there is a possible solution suggested under error_reporting:

<?php

error_reporting
(E_ALL);

ini_set("display_errors", 1);

include(
"file_with_errors.php");

?>

[Modified by moderator]

You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).


ohcc at 163 dot com

6 years ago


If you set the error_log directive to a relative path, it is a path relative to the document root rather than php's containing folder.

Roger

3 years ago


When `error_log` is set to a file path, log messages will automatically be prefixed with timestamp [DD-MMM-YYYY HH:MM:SS UTC].  This appears to be hard-coded, with no formatting options.

php dot net at sp-in dot dk

8 years ago


There does not appear to be a way to set a tag / ident / program for log entries in the ini file when using error_log=syslog.  When I test locally, "apache2" is used.
However, calling openlog() with an ident parameter early in your script (or using an auto_prepend_file) will make PHP use that value for all subsequent log entries. closelog() will restore the original tag.

This can be done for setting facility as well, although the original value does not seem to be restored by closelog().


iio7 at protonmail dot com

1 year ago


It's important to note that when display_errors is "on", PHP will send a HTTP 200 OK status code even when there is an error. This is not a mistake or a wrong behavior, but is because you're asking PHP to output normal HTML, i.e. the error message, to the browser.

When display_errors is set to "off", PHP will send a HTTP 500 Internal Server Error, and let the web server handle it from there. If the web server is setup to intercept FastCGI errors (in case of NGINX), it will display the 500 error page it has setup. If the web server cannot intercept FastCGI errors, or it isn't setup to do it, an empty screen will be displayed in the browser (the famous white screen of death).

If you need a custom error page but cannot intercept PHP errors on the web server you're using, you can use PHPs custom error and exception handling mechanism. If you combine that with output buffering you can prevent any output to reach the client before the error/exception occurs. Just remember that parse errors are compile time errors that cannot be handled by a custom handler, use "php -l foo.php" from the terminal to check for parse errors before putting your files on production.


jaymore at gmail dot com

6 years ago


Document says
So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).

But it is better to set "-1" as the E_ALL value.
For example, in httpd.conf or .htaccess, use
php_value error_reporting -1
to report all kind of error without be worried by the PHP version.


Introduction

PHP is a server-side scripting language used in web development. As a scripting language, PHP is used to write code (or scripts) to perform tasks. If a script encounters an error, PHP can generate an error to a log file.

In this tutorial, learn how to enable PHP Error Reporting to display all warnings. We also dive into creating an error log file in PHP.

Guide on enabling php errors and reporting

What is a PHP Error?

A PHP error occurs when there is an issue within the PHP code. Even something simple can cause an error, such as using incorrect syntax or forgetting a semicolon, which prompts a notice. Or, the cause may be more complex, such as calling an improper variable, which can lead to a fatal error that crashes your system.

If you do not see errors, you may need to enable error reporting.

To enable error reporting in PHP, edit your PHP code file, and add the following lines:

<?php
error_reporting(E_ALL);
?>

You can also use the ini_set command to enable error reporting:

<?php
ini_set('error_reporting', E_ALL);
?>

Edit php.ini to Enable PHP Error Reporting

If you have set your PHP code to display errors and they are still not visible, you may need to make a change in your php.ini file.

On Linux distributions, the file is usually located in /etc/php.ini folder.

Open php.ini in a text editor.

Then, edit the display_errors line to On.

This is an example of the correction in a text editor:

php.ini file to enable error reporting to display notifications

Edit .htaccess File to turn on Error Reporting

The .htaccess file, which acts as a master configuration file, is usually found in the root or public directory. The dot at the beginning means it’s hidden. If you’re using a file manager, you’ll need to edit the settings to see the hidden files.

Open the .htaccess file for editing, and add the following:

php_flag display_startup_errors on
php_flag display_errors on

If these values are already listed, make sure they’re set to on.

Save the file and exit.

Other Useful Commands

To display only the fatal warning and parse errors, use the following:

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>

You can add any other error types you need. Just separate them with the pipe | symbol.

This list contains all the predefined constants for PHP error types.

One useful feature is the “not” symbol.

To exclude a particular error type from reporting:

<?php
error_reporting(E_ALL & ~E_NOTICE)
?>

In this example, the output displays all errors except for notice errors.

How to Turn Off PHP Error Reporting

To turn off or disable error reporting in PHP, set the value to zero. For example, use the code snippet:

<?php
error_reporting(0);
?>

How to Create an Error Log File in PHP

Error logs are valuable resources when dealing with PHP issues.

To display PHP error logs, edit the .htaccess file by adding the following:

php_value error_log logs/all_errors.log

If you don’t have access to the .htaccess file, you can edit the httpd.conf or apache2.conf file directly.

This log is typically stored in the /var/log/httpd/ or /var/log/apache2/ directory.

To enable error logging, edit your version of the file and add the following:

ErrorLog “/var/log/apache2/website-name-error.log”

You may substitute httpd for apache2 if needed. Likewise, if you’re using nginx, you can use that directory for the error log.

How to Display PHP Errors on a Webpage

Error logs are valuable resources when dealing with PHP issues.

To display PHP error logs, edit the .htaccess file by adding the following:

php_value error_log logs/all_errors.log

If you don’t have access to the file, you can edit the httpd.conf or apache2.conf file directly.

This log is typically stored in the /var/log/httpd/ or /var/log/apache2/ directory.

To enable error logging, edit your version of the file and add the following:

ErrorLog “/var/log/apache2/website-name-error.log”

You may substitute httpd for apache2 if needed. Likewise, if you’re using nginx, you can use that directory for the error log.

Conclusion

This tutorial has provided you with multiple alternatives to enable and show all PHP errors and warnings. By receiving error notifications quickly and accurately, you can improve the ability to troubleshoot PHP issues. If you are implementing new features, installing a new PHP-based app, or trying to locate a bug on your website, it is important to know which PHP version your web server is running before taking any steps.

In PHP, we can decide whether to show an error to end-users or not. You can enable or disable error reporting in PHP with three approaches:

Approach 1: In the php.ini file, we can set the display_error parameter as on or off. The on means errors are displayed and off means no errors to display and report. To do so, open the “php.ini” file and search for the display_error parameter and change it to value on. Save the file. Restart all services of the webserver. Now it will display all the errors of the PHP script to the end-users. To disable the error reporting, set the display_error parameter to off. The off parameter means it will not show any error to users.

Approach 2: The second approach to enable or disable error reporting is using the ini_set() function. It is an inbuilt function available in PHP to change the configuration settings available in the php.ini file. It takes two parameters, the first is the setting name you want to modify and the second is the value you want to assign.

If you want to change the value of the display_error parameter of the php.ini file

Enable the error reporting: It will enable error reporting.

ini_set("display_errors", "1") 

Disable the error reporting: It will disable the error reporting.

ini_set("display_errors", "0")

Example 1: In the code, we have enabled error reporting so it displays the error to the user. The “printname()” function is “undefined” because the name of the defined function is “printmyname()”.

PHP

<?php

   ini_set('display_errors','1');

  function printmyname()

  {

     echo "My name is GeeksforGeeks";

  }

  printname();

?>

Output:

Fatal error: Call to undefined function printname()

Example 2: The following code will turn off showing the error to users.

PHP

<?php

  ini_set('display_errors','0');

  function printmyname()

  {

     echo "My name is GeeksforGeeks";

  }

  printname();

?>

Output:

This page isn’t working. localhost is 
currently unable to handle this request.
HTTP ERROR 500

Approach 3: This approach can also be used to enable error reporting by using the error_reporting() function, which is a native PHP function that sets the error_reporting directive at runtime, i.e., it is used to sets which PHP errors are reported. This function also helps to set the different levels for the runtime (duration) of your script, as PHP contains various levels of error. This function accepts error names like E_ERROR, E_PARSE, E_WARNING, etc, as parameters, thereby allowing that specified errors to report. A few errors that occur in PHP are listed below:

  • E_PARSE: The compile-time error generated by the parser.
  • E_ERROR: Fatal runtime error-execution of script get’s halted.
  • E_WARNING: Non-fatal runtime error-execution of script get’s halted.
  • E_CORE_ERROR: Fatal errors occur during the initial startup of the script.
  • E_CORE_WARNING: Non-fatal errors occur during the initial startup of the script.
  • E_NOTICE: The script found something that might be an error.
  • E_ALL: Includes all errors and warnings.

Syntax:

error_reporting(error_names);

Parameter value:

  • error_names: It specifies the name of errors that will pass as an argument.

Note: The error_reporting() function also accepts integer 0 which turns off all error reporting and -1 turns on all error reporting.

Example 3: The below code represents how to use the error_reporting() function in a PHP script.

PHP

<?php

    error_reporting(E_ERROR | E_WARNING);

    error_reporting(E_ALL);

    error_reporting(E_ALL & ~E_PARSE);

    error_reporting(-1);

    error_reporting(0);

    echo "Sample error reporting code using error_reporting function";

?>

Output:

Sample error reporting code using error_reporting function

В этом руководстве мы расскажем о различных способах того, как в PHP включить вывод ошибок. Мы также обсудим, как записывать ошибки в журнал (лог).

Как быстро показать все ошибки PHP

Самый быстрый способ отобразить все ошибки и предупреждения php — добавить эти строки в файл PHP:

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

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

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

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

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

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

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

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

display_errors = on

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

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

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

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

php_flag display_startup_errors on
php_flag display_errors on

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

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

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

php_value error_log logs/all_errors.log

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

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

error_reporting(E_WARNING);

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

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

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

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

error_reporting(0);

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

error_reporting(E_NOTICE);

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

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

error_reporting(E_ALL & ~E_NOTICE);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Пример для Apache:

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

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

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

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

Понравилась статья? Поделить с друзьями:
  • Error resolving address
  • Error reporting e error e parse
  • Error resolution 1693x810 is not supported
  • Error resizing partition ubuntu
  • Error reporting e all ini set