PHP Doku:: Gibt an, welche PHP-Fehlermeldungen angezeigt werden - function.error-reporting.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDas Verhalten von PHP beeinflussenFehlerbehandlung und ProtokollierungFehlerbehandlungsfunktionenerror_reporting

Ein Service von Reinhard Neidl - Webprogrammierung.

Fehlerbehandlungsfunktionen

<<error_log

restore_error_handler>>

error_reporting

(PHP 4, PHP 5)

error_reporting Gibt an, welche PHP-Fehlermeldungen angezeigt werden

Beschreibung

int error_reporting ([ int $level ] )

Mit error_reporting() wird die error_reporting Direktive zur Laufzeit des Programms gesetzt. In PHP gibt es viele Stufen für die Anzeige von Fehlermeldungen, die mit dieser Funktion für die Dauer der Programmausführung eingestellt werden kann.

Parameter-Liste

level

Das neue error_reporting Level. Es können sowohl eine numerische Bitmaske als auch benannte Konstanten übergeben werden. Der Einsatz benannter Konstanten wird empfohlen um die Kompatibilität mit zukünftigen Versionen sicherzustellen. Wann immer Error Level Konstanten hinzugefügt werden erweitert sich der genutzte Integerbereich so das ältere Integerkonstanten nicht unbedingt weiter das erwartete Verhalten zeigen.

Die folgende Tabelle listet die verfügbaren Konstanten auf. Die Bedeutung der jeweiligen Error Level finden Sie im Abschnitt predefined constants.
error_reporting() Level Konstanten und Bit-Werte
value constant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR
8192 E_DEPRECATED
16384 E_USER_DEPRECATED

Rückgabewerte

Gibt den bisherigen error_reporting Wert zurück level.

Changelog

Version Beschreibung
5.0.0 E_STRICT wurde hinzugefügt (ist aber nicht Teil von E_ALL).
5.2.0 E_RECOVERABLE_ERROR wurde hinzugefügt.
5.3.0 E_DEPRECATED und E_USER_DEPRECATED wurden hinzugefügt.
6 E_STRICT ist nun in E_ALL enthalten.

Beispiele

Beispiel #1 error_reporting() Beispiel

<?php

// Error Reporting komplett abschalten
error_reporting(0);

// Nur einfache Fehler melden
error_reporting(E_ERROR E_WARNING E_PARSE);

// E_NOTICE ist sinnvoll um uninitialisierte oder
// falsch geschriebene Variablen zu entdecken
error_reporting(E_ERROR E_WARNING E_PARSE E_NOTICE);

// Melde alle Fehler außer E_NOTICE
// Dies ist der Vorgabewert in php.ini
error_reporting(E_ALL E_NOTICE);

// Melde alle PHP Fehler
error_reporting(E_ALL);

// Dies entspricht error_reporting(E_ALL);
ini_set('error_reporting'E_ALL);

?>

Anmerkungen

Warnung

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

Siehe auch


28 BenutzerBeiträge:
- Beiträge aktualisieren...
rojaro at gmail dot com
6.12.2010 11:55
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

<?php error_reporting(-1); ?>
keithm at aoeex dot com
14.06.2010 19:23
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.
roberto at spadim dot com dot br
29.01.2010 22:00
see more information about php 5.3 deprecated errors

http://php.net/manual/en/migration53.deprecated.php
misplacedme at gmail dot com
9.06.2009 23:25
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.
?>
ecervetti at orupaca dot fr
25.03.2009 10:54
It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135
Daz Williams (The Northeast)
18.02.2009 15:03
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.
info at hephoz dot de
14.08.2008 15:34
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!
kc8yds at gmail dot com
10.08.2008 20:45
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);
?>
derek at darkcolors dot com
27.05.2008 10:12
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.
bbaez at biospectra dot com
10.05.2007 2:02
frederick noted this in 2005 but want to stress the point here

If you set error_reporting in httpd.conf or within a script (some PHP versions) then you must use the integer value and not the string:

Example httpd.conf:
E_ALL ^ E_NOTICE would be:
php_value error_reporting 6135

otherwise the error will not display during output.
antickon AT gmail.com
4.04.2007 14:21
regarding what vdephily at bluemetrix dot com said ( see http://be.php.net/manual/en/function.error-reporting.php#50228 )

<?php
echo $foobar->field;
?>

also initializes $foobar (as an instance of stdClass), so this code will not cause any notices.
bitagenda at gmail dot com
9.03.2007 5:36
A simple and effective way to catch Fatal errors.
From here you can go forward with your own ideas and elaborate a detailed error report.

The principle is simple and ready to test on your system

Fatal errors are not currently catched and you should have display errors off in production sites, but may be you need to test the system so you want a fast an easy way to see fatal errors in your currently running site, without the users seeing those Fatal errors as recomended.

You must have this function

<?php
function catchFatalErrors($p_OnOff='On'){
   
ini_set('display_errors','On');
   
$phperror='><div id="phperror" style="display:none">';
   
ini_set('error_prepend_string',$phperror);
   
$phperror='</div>><form name="catcher" action="/sos.php" method="post" ><input type="hidden" name="fatal"  value=""></form> <script> document.catcher.fatal.value = document.getElementById("phperror").innerHTML; document.catcher.submit();</script>';
   
ini_set('error_append_string',$phperror);
}

Now activate your fatal error catcher

catchFatalErrors
();
?>

Just to test write this inexistent function

<?php
    Bitagenda
();
?>

That's all. As you can see there will be a form posted with action="/sos.php", of course you can name this page at your liking, in this case is at the site's root.

Have ready your page sos.php, and elaborate on that. Of course change the mail address to yours,and display a message to the user at your liking.

<?php
if (isset($_POST['fatal'])){
 
error_log($_POST['fatal'],1,'bitagenda@gmail.com');
}
?>

 "System Out of Service. Thanks for waiting."

The other fact about this handler is that even if you do not redirect the Fatal Error, prepending
><div style="display:none">
and appending
</div>

Then writting yor personal message

" Sorry, fatal bug."

Will hide the fatal error message from the user, but will be visible in the browsers soure code view.

What happens if you redirect the page before displaying the error? I don´t know, have not tested, but at least you could do it to alert you that a fatal error exists and possibly the fatal error is not displayed (leading to security and at the same time catching the fatal error). Then you could activate this error handler with post-redirection to see what's going on.

;o)

Bitagenda
Alex
19.01.2007 12:43
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.
silvan at NOSPAM dot example dot com
4.10.2006 15:38
On a shared debugging and production server it is convenient to use
<?php error_reporting(E_ALL); ?>
for debugging.

This will not help in case of parsing errors, so make sure you enable at least E_PARSE in your php.ini. Parse errors should not exist in production scripts.

Still, sometimes your script will not get executed even though no parse error is displayed (just a blank page/ no output at all). As far as I know this only happens when you redeclare a user function or class.

eg.
<?php
error_reporting
(E_ALL);

function
a(){}
function
a(){}
?>

This prevents your script from running like a parse error, but is in fact a fatal run-time error (E_ERROR). Other fatal run-time errors will allow your script to apply the error_reporting, when it is executed before the
error occurs (eg. put error_reporting on the first line of code.)
Chris
9.05.2006 22:32
I found some simple mistakes in the functions I posted yesterday, so here are the corrected versions.
And a good advice: never code in the middle of the night ;)

<?php
function error2string($value)
{
   
$level_names = array(
       
E_ERROR => 'E_ERROR', E_WARNING => 'E_WARNING',
       
E_PARSE => 'E_PARSE', E_NOTICE => 'E_NOTICE',
       
E_CORE_ERROR => 'E_CORE_ERROR', E_CORE_WARNING => 'E_CORE_WARNING',
       
E_COMPILE_ERROR => 'E_COMPILE_ERROR', E_COMPILE_WARNING => 'E_COMPILE_WARNING',
       
E_USER_ERROR => 'E_USER_ERROR', E_USER_WARNING => 'E_USER_WARNING',
       
E_USER_NOTICE => 'E_USER_NOTICE' );
    if(
defined('E_STRICT')) $level_names[E_STRICT]='E_STRICT';
   
$levels=array();
    if((
$value&E_ALL)==E_ALL)
    {
       
$levels[]='E_ALL';
       
$value&=~E_ALL;
    }
    foreach(
$level_names as $level=>$name)
        if((
$value&$level)==$level) $levels[]=$name;
    return
implode(' | ',$levels);
}
?>

<?php
function string2error($string)
{
   
$level_names = array( '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', 'E_ALL' );
    if(
defined('E_STRICT')) $level_names[]='E_STRICT';
   
$value=0;
   
$levels=explode('|',$string);
    foreach(
$levels as $level)
    {
       
$level=trim($level);
        if(
defined($level)) $value|=(int)constant($level);
    }
    return
$value;
}
?>
the_bug_the_bug at hotmail dot com
24.04.2006 15:20
In response to simon at firepages dot com dot au below:

I wrote a shorter more efficient function which will return a string containing the names of the error levels set in the .ini file:

<?php
function error_level_tostring($intval, $separator)
{
   
$errorlevels = array(
       
2047 => 'E_ALL',
       
1024 => 'E_USER_NOTICE',
       
512 => 'E_USER_WARNING',
       
256 => 'E_USER_ERROR',
       
128 => 'E_COMPILE_WARNING',
       
64 => 'E_COMPILE_ERROR',
       
32 => 'E_CORE_WARNING',
       
16 => 'E_CORE_ERROR',
       
8 => 'E_NOTICE',
       
4 => 'E_PARSE',
       
2 => 'E_WARNING',
       
1 => 'E_ERROR');
   
$result = '';
    foreach(
$errorlevels as $number => $name)
    {
        if ((
$intval & $number) == $number) {
           
$result .= ($result != '' ? $separator : '').$name; }
    }
    return
$result;
}
?>

P.S. With a little modification this function can be made to show the string values of any enumeration.
dave at davidhbrown dot us
6.04.2006 17:51
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.
DarkGool
19.08.2005 19:30
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
...
fredrik at demomusic dot nu
23.07.2005 1:24
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?
phpfanat at yandex dot ru
22.02.2005 18:03
If you get a weird mysql warnings like "Warning: mysql_query() [http://www.mysql.com/doc]: 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

And, as of my opinion, it should be NOTICE, not WARNING level.
vdephily at bluemetrix dot com
22.02.2005 12:40
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
?>
Fernando Piancastelli
13.12.2004 22:23
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.
ferozzahid [at] usa [dot] com
8.09.2004 13:31
To be enable to switch between error_reporting during development and release phases, one can define say 'php_error_reporting' in the main configuration file (ini like file: no PHP) for the application as:

# config.ini
# PHP error reporting. supported values are given below.
# 0 - Turn off all error reporting
# 1 - Running errors
# 2 - Running errors + notices
# 3 - All errors except notices and warnings
# 4 - All errors except notices
# 5 - All errors

php_error_reporting=4

# config.ini ends

Setting error_reporting in PHP files would be something like the code below, assuming the function getinivar() returns the variable value from the configuration file.

<?php
// setting PHP error reporting
switch(getinivar('php_error_reporting')) {
case
0: error_reporting(0); break;
case
1: error_reporting(E_ERROR | E_WARNING | E_PARSE); break;
case
2: error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); break;
case
3: error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); break;
case
4: error_reporting(E_ALL ^ E_NOTICE); break;
case
5: error_reporting(E_ALL); break;
default:
   
error_reporting(E_ALL);
}
?>

Feroz Zahid.
jernberg at fairytale dot se
27.02.2003 12:27
tip: if you want your error_reporting()-setting to work with your own error handler you could simply check the error number against the current error bitmask.

<?php
function myErrorHandler( $errno, $errstr, $errfile, $errline )
{
 
$replevel = error_reporting();
  if( (
$errno & $replevel ) != $errno )
  {
   
// we shall remain quiet.
   
return;
  }
  echo(
"error....." );
}
?>
rbt at zort.ca
10.02.2002 5:25
It should be noted that in apache.conf files the defined values (constants) don't work.  For E_ALL logging, one would use:

php_admin_value error_reporting 2047
j dot schriver at vindiou dot com
3.10.2000 8:37
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]

3.02.2000 20:31
The E_NOTICE error reporting level reports the use of undefined variables as an error.

For example:
error_reporting(E_ALL); # Set error reporting to highest level
if ($foo)            # This will generate an error
  print "bar";       # because $foo is not defined

To avoid this behavior, use isset to test if the given
variable has been defined.

For example:
error_reporting(E_ALL);
if (isset ($foo))
    print "bar";

webmaster at l-i-e dot com
21.05.1999 23:13
[Editor's Note: E_ALL will contain the result of OR'ing all of the applicable error constants together. For PHP 3, this will be the first 4 E_xxx constants.  For PHP 4, this will be all constants. ]

There is also an E_ALL which is the first 4 E_xxx added up for you...



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)