php[tek] 2018 : Call for Speakers

error_reporting

(PHP 4, PHP 5, PHP 7)

error_reportingSets which PHP errors are reported

Description

int error_reporting ([ int $level ] )

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional level is not set, error_reporting() will just return the current error reporting level.

Parameters

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 level parameter is given.

Changelog

Version Description
5.4.0 E_STRICT became part of E_ALL.
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not part of E_ALL).

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 (see changelog)
error_reporting(E_ALL);

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

// Same as error_reporting(E_ALL);
ini_set('error_reporting'E_ALL);

?>

Notes

Warning

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).

Tip

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 5.4.

See Also

add a note add a note

User Contributed Notes 29 notes

up
267
info at hephoz dot de
9 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!
up
21
dave at davidhbrown dot us
11 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.
up
14
keithm at aoeex dot com
7 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.
up
6
ecervetti at orupaca dot fr
8 years ago
It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135
up
4
Fernando Piancastelli
12 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.
up
7
misplacedme at gmail dot com
8 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.
?>
up
1
chris at ocproducts dot com
1 year ago
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
up
3
rojaro at gmail dot com
6 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); ?>
up
2
DarkGool
12 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
...
up
1
forcemdt
4 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();
  }
up
2
j dot schriver at vindiou dot com
17 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]
up
2
fredrik at demomusic dot nu
12 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?
up
1
Alex
10 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.
up
-1
adam at adamhahn dot com
8 months 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
);
?>
up
1
vdephily at bluemetrix dot com
12 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
?>
up
1
Daz Williams (The Northeast)
8 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.
up
0
Rash
2 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.
up
-1
Chris
11 years ago
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;
}
?>
up
-3
teynon1 at gmail dot com
5 years ago
id="Hcom65884">
inclut">E_COMPILE_ERRin to error_report. ;)
So a "rre erdatf gmsace.
<?">;
&nbs />error_reporting
(, E_WARNING , );
;
&nbsd">function
(, , , {
   
Dound shy thAll othte nn); outpve mess.LL,
   
true= ();
;
&nbsrre erd">,
);
?>
inclut">E_COMPILE_ERRin at the error_reportn 0.

<?php
&nbs />error_reporting
(, E_WARNING , , E_COMPILE_ERon");
/>
?>
up
-3
8 years ago
id="Hcom65884">
'E_STR r, as (fll othed versi j/>Juof E_on:

anyonuiseee isyyouoblemslf, wias xamas the corred, thpr host

<?php
ini_set
('error_reporting', &lode(,,?&=ICT'(,,&ICT'E_ALLE_STRICTE_ALL);
?>
up
2
11 years ago
not o shd in debugg r, a ocprodration servas it convopie want s="r :
<?" />error_reporting(E_ALL, ?>
&setting ersday, ld masurd"if yTo enab thamastOR, E_PAelp th yoto php.. Pacourhe errors shouis non-exelp ocprodratiog Scrsace.
&sable err Th">'displizej/>Jua blankter p">// ); outputroll). Aros yeaionsknthrd, tho> Onhappesi ng whif yshdean herphp usd">functi (fen cl. ;)
<?php
error_reporting
(E_ALL);
function
function
?>
&sable erles, biakes facJua fas="r), -him ble err(PILE_ER). Ol othfas="r), -him ble ersion willlthres riog Scrhis tpsimpat the error_report, ng whas it execurectbep; fpat tphp
er oe acs (egn outpue error_reporti upon tfir>Jund ling ofde.)n>
up
-4 0
2 years ago
ll nly displon tE_DEPRECATEDble ersi()" for examplf, w abochangunning tre>Jule of tur configurati:php
error_report("> error_reportingLL &am(-1 ^tE_DEPRECATED));n>
up
-3
10 years ago
in h://bnote.php.f="/manuen/ge=function.error-reportote.f="#50ra;< t ;)

<?php
'foo />=>
?>
'foo (ae is anconscling stdCn cl)day, d, ther cond will ncato uisyyor/notress.
up
-3
2 years ago
beyTo enabnt tf, ch betwr beue error_reportidu striHP developmer, arelmas tphas s, onuier ct">defich ' />p">'error_reportiode in tha0) in configuratint filen 54% lint fce : PHP)as (fet the licguratiasuse:
$vaions aay g canfol. />
p">'error_report=4se:
functiaeten var(())) retsing ted varia>// valun from the configuratint fr...

<?php
en settihe Pof error reportphp
(('error_reportivel />{ (0((0{ (0((, E_WARNING , 0{ (0((, E_WARNING , , 0{ (0(((, E_WARNvel{ (0((0{ (((0{     error_reportingE_ALL);
}
?>
up
2
2 years ago
If y>I want teerollthe errolp th yolocalthnvi/stcomm, if yer cis sth yotrojorreURL51% li"">'fot clocal"olocalphil, a aboutaxelp booter spint fr ;)

<?php
(if($_SERVER[,] = {
   
ini_set('display_errors'(0);
   
ini_set('error_reporting', E_ALL);
   
or to error_reportit">E_d">);
/>
?>
up
-3
2 years ago

in h://te.php.f="/manuen/migigurat53.deprecarecote.ra;
5 -3
8 years ago
hadrom touoblemoutaxele of fpwae is le erlet;?"isshouj/>Juay g meua blankter p.p; &nbsAr any errutroll()" cedua blankter p ancoeadro/>anyn); outpctaxsoeservers ev althouI madmasurd"utaxe">hadrog error_reportien ant t">E_, ">'display_errc reteduatioetcoetc.p; &nbsButp), simp), running tnt fii>notonffecurrtdicorroryslllthortet nt tothray_err! 0.
nat tonuidicorroryswae fuf a(2.0 Gb).p; &nbsItheaseding tnt fil, anthray_errons a">'displiznormg"ta.p; &nbsIpant mdealsoeor hers tretuny err a gunnioffess.