Error reporting e all ini set

(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');
}

This always works for me:

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

However, this doesn’t make PHP to show parse errors occurred in the same file — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

Note that above recommentdtion is only suitable for the dev environment. On a live site display_errors must be set to 0, while log_errors to 1. And then you’ll be able to see all errors in the error log.

In case of AJAX call, on a dev server open DevTools (F12), then Network tab.
Then initiate the request which result you want to see, and it will appear in the Network tab. Click on it and then the Response tab. There you will see the exact output.
While on a live server just check the error log all the same.

Your Common Sense's user avatar

answered Jan 29, 2014 at 11:25

Fancy John's user avatar

Fancy JohnFancy John

37.5k3 gold badges26 silver badges25 bronze badges

16

You can’t catch parse errors in the same file where error output is enabled at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.

This question may provide additional info.

Your Common Sense's user avatar

answered Jun 27, 2009 at 19:14

Michael Madsen's user avatar

Michael MadsenMichael Madsen

53.8k7 gold badges72 silver badges83 bronze badges

0

Inside your php.ini:

display_errors = on

Then restart your web server.

j0k's user avatar

j0k

22.4k28 gold badges80 silver badges89 bronze badges

answered Jan 8, 2013 at 9:27

user1803477's user avatar

user1803477user1803477

1,5951 gold badge9 silver badges4 bronze badges

5

To display all errors you need to:

1. Have these lines in the PHP script you’re calling from the browser (typically index.php):

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

2.(a) Make sure that this script has no syntax errors

—or—

2.(b) Set display_errors = On in your php.ini

Otherwise, it can’t even run those 2 lines!

You can check for syntax errors in your script by running (at the command line):

php -l index.php

If you include the script from another PHP script then it will display syntax errors in the included script. For example:

index.php

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

// Any syntax errors here will result in a blank screen in the browser

include 'my_script.php';

my_script.php

adjfkj // This syntax error will be displayed in the browser

answered Jan 29, 2014 at 9:52

andre's user avatar

andreandre

1,8311 gold badge16 silver badges8 bronze badges

2

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

Peter Mortensen's user avatar

answered May 18, 2013 at 15:01

Kalhua's user avatar

KalhuaKalhua

5594 silver badges2 bronze badges

1

Warning: the below answer is factually incorrect. Nothing has been changed in error handling, uncaught exceptions are displayed just like other errors. Suggested approach must be used with caution, because it outputs errors unconditionally, despite the display_error setting and may pose a threat by revealing the sensitive information to an outsider on a live site.

You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:

try{
     // Your code
} 
catch(Error $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):

try{
     // Your code
} 
catch(Throwable $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Your Common Sense's user avatar

answered Mar 28, 2016 at 19:26

Frank Forte's user avatar

Frank ForteFrank Forte

1,89518 silver badges18 bronze badges

9

This will work:

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

Peter Mortensen's user avatar

answered May 5, 2014 at 13:23

Mahendra Jella's user avatar

Mahendra JellaMahendra Jella

5,2901 gold badge32 silver badges38 bronze badges

1

Use:

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

This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:

php -l phpfilename.php

Peter Mortensen's user avatar

answered May 4, 2016 at 19:14

Abhijit Jagtap's user avatar

Abhijit JagtapAbhijit Jagtap

2,7152 gold badges32 silver badges43 bronze badges

0

Set this in your index.php file:

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

Peter Mortensen's user avatar

answered Sep 26, 2017 at 12:32

Sumit Gupta's user avatar

Sumit GuptaSumit Gupta

5674 silver badges12 bronze badges

0

Create a file called php.ini in the folder where your PHP file resides.

Inside php.ini add the following code (I am giving an simple error showing code):

display_errors = on

display_startup_errors = on

Peter Mortensen's user avatar

answered Mar 31, 2015 at 18:38

NavyaKumar's user avatar

NavyaKumarNavyaKumar

5895 silver badges3 bronze badges

In order to display a parse error, instead of setting display_errors in php.ini you can use a trick: use include.

Here are three pieces of code:

File: tst1.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Missing " and ;
echo "Testing

When running this file directly, it will show nothing, given display_errors is set to 0 in php.ini.

Now, try this:

File: tst2.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include ("tst3.php");

File: tst3.php

<?php
// Missing " and ;
echo "Testing

Now run tst2.php which sets the error reporting, and then include tst3. You will see:

Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4

Your Common Sense's user avatar

answered May 20, 2017 at 12:07

Peter's user avatar

PeterPeter

1,24319 silver badges32 bronze badges

4

If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');

Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:

//file1.php
namespace ab;
class x {
    ...
}

//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
    ...
}

answered Apr 24, 2015 at 2:55

jxmallett's user avatar

jxmallettjxmallett

4,0571 gold badge28 silver badges35 bronze badges

2

I would usually go with the following code in my plain PHP projects.

if(!defined('ENVIRONMENT')){
    define('ENVIRONMENT', 'DEVELOPMENT');
}

$base_url = null;

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'DEVELOPMENT':
            $base_url = 'http://localhost/product/';
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL);
            break;

        case 'PRODUCTION':
            $base_url = 'Production URL'; /* https://google.com */
            error_reporting(E_ALL);
            ini_set('display_errors', 0);
            ini_set('display_startup_errors', 0);
            ini_set('log_errors', 1); // Mechanism to log errors
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

Your Common Sense's user avatar

answered Feb 1, 2017 at 7:16

Channaveer Hakari's user avatar

If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:

find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"

If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:

<?php
if( !ini_set( 'display_errors', 1 ) ) {
  echo "display_errors cannot be set.";
} else {
  echo "changing display_errors via script is possible.";
}

answered Jan 11, 2016 at 12:11

chiborg's user avatar

chiborgchiborg

26.1k12 gold badges98 silver badges114 bronze badges

1

You can do something like below:

Set the below parameters in your main index file:

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

Then based on your requirement you can choose which you want to show:

For all errors, warnings and notices:

    error_reporting(E_ALL); OR error_reporting(-1);

For all errors:

    error_reporting(E_ERROR);

For all warnings:

    error_reporting(E_WARNING);

For all notices:

    error_reporting(E_NOTICE);

For more information, check here.

Peter Mortensen's user avatar

answered Feb 1, 2017 at 7:33

Binit Ghetiya's user avatar

Binit GhetiyaBinit Ghetiya

1,8592 gold badges23 silver badges31 bronze badges

1

You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.

function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");

Peter Mortensen's user avatar

answered Jun 4, 2017 at 14:41

lintabá's user avatar

lintabálintabá

7319 silver badges18 bronze badges

Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log

answered Jan 8, 2022 at 22:17

webcoder.co.uk's user avatar

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

Peter Mortensen's user avatar

answered May 9, 2017 at 3:28

Joel Wembo's user avatar

Joel WemboJoel Wembo

8146 silver badges10 bronze badges

The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.

try {
    // Page code
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

Peter Mortensen's user avatar

answered Mar 27, 2017 at 2:31

Xakiru's user avatar

XakiruXakiru

2,4381 gold badge14 silver badges11 bronze badges

3

    <?php
    // Turn off error reporting
    error_reporting(0);

    // Report runtime errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    // Report all errors
    error_reporting(E_ALL);

    // Same as error_reporting(E_ALL);
    ini_set("error_reporting", E_ALL);

    // Report all errors except E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ?>

While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.

Lahiru Mirihagoda's user avatar

answered May 24, 2018 at 8:48

pardeep's user avatar

pardeeppardeep

3491 gold badge5 silver badges7 bronze badges

0

Just write:

error_reporting(-1);

answered Jan 13, 2017 at 18:56

jewelhuq's user avatar

jewelhuqjewelhuq

1,19014 silver badges19 bronze badges

0

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

Peter Mortensen's user avatar

answered Oct 19, 2017 at 5:45

Peter Haberkorn's user avatar

If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:

php -ddisplay_errors=1 script.php

Peter Mortensen's user avatar

answered Oct 24, 2019 at 23:11

gvlasov's user avatar

gvlasovgvlasov

17.8k19 gold badges69 silver badges106 bronze badges

Report all errors except E_NOTICE

error_reporting(E_ALL & ~E_NOTICE);

Display all PHP errors

error_reporting(E_ALL);  or ini_set('error_reporting', E_ALL);

Turn off all error reporting

error_reporting(0);

answered Dec 31, 2019 at 10:07

Shaikh Nadeem's user avatar

In Unix CLI, it’s very practical to redirect only errors to a file:

./script 2> errors.log

From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:

fwrite(STDERR, "Debug infosn"); // Write in errors.log^

Then from another shell, for live changes:

tail -f errors.log

or simply

watch cat errors.log

answered Nov 26, 2019 at 2:28

NVRM's user avatar

NVRMNVRM

10.6k1 gold badge82 silver badges85 bronze badges

2

If you are on a SharedHosting plan (like on hostgator)… simply adding

php_flag display_errors 1

into a .htaccess file and uploading it to the remote folder may not yield the actual warnings/errors that were generated on the server.

What you will also need to do is edit the php.ini

This is how you do it via cPanel (tested on hostgator shared hosting
plan)

After logging into your cPanel, search for MultiPHP INI Editor.
It is usually found under the SOFTWARE section in your cPanel list of items.

On the MultiPHP INI Editor page …you can stay on the basic mode tab and just check the button on the line that says display_errors.
Then click the Apply button to save.

enter image description here

IMPORTANT: Just remember to turn it back off when you are done debugging; because this is not recommended for public servers.

answered Mar 13, 2022 at 17:21

Really Nice Code's user avatar

Really Nice CodeReally Nice Code

1,0141 gold badge12 silver badges21 bronze badges

As it is not clear what OS you are on these are my 2 Windows cents.
If you are using XAMPP you need to manually create the logs folder under C:xamppphp. Not your fault, ApacheFriends ommitted this.

To read and follow this file do.

Get-Content c:xamppphplogsphp_error_log -Wait

To do this in VSCode create a task in .vscodetasks.json

{ 
  // See https://go.microsoft.com/fwlink/?LinkId=733558 
  // for the documentation about the tasks.json format 
  "version": "2.0.0", 
  "tasks": [ 
    { 
      "label": "Monitor php errors", 
      "type": "shell", 
      "command": "Get-Content -Wait c:\xampp\php\logs\php_error_log", 
      "runOptions": { 
        "runOn": "folderOpen" 
      } 
    } 
  ] 

and have it run on folder load.

answered Dec 3, 2022 at 14:40

theking2's user avatar

theking2theking2

1,8101 gold badge24 silver badges30 bronze badges

В этом руководстве мы расскажем о различных способах того, как в 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_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 дает
тот же результат.

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

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

Поведение этих функций зависит от установок в 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.


PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:

  • E_ALL – все ошибки,
  • 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 – уведомления пользователей.

1

Вывод ошибок в браузере

error_reporting(E_ALL);
ini_set('display_errors', 'On'); 

PHP

В htaccess

php_value error_reporting "E_ALL"
php_flag display_errors On

htaccess

На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.

2

Запись ошибок в лог файл

error_reporting(E_ALL);
ini_set('display_errors', 'Off'); 
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');

PHP

Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:

Order Allow,Deny
Deny from all

htaccess

Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):

<FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
Order Allow,Deny
Deny from all
</FilesMatch>

htaccess

3

Отправка ошибок на e-mail

Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.

Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.

register_shutdown_function('error_alert');

function error_alert() 
{ 
	$error = error_get_last();
	if (!empty($error)) {
		mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); 
	}
}

PHP

Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.

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

function error_alert($type, $message, $file, $line, $vars)
{
	$error = array(
		'type'    => $type,
		'message' => $message,
		'file'    => $file,
		'line'    => $line
	);
	error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
}

set_error_handler('error_alert');

PHP

4

Пользовательские ошибки

PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():

trigger_error('Пользовательская ошибка', E_USER_ERROR);

PHP

Результат:

Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
  • E_USER_ERROR – критическая ошибка,
  • E_USER_WARNING – не критическая,
  • E_USER_NOTICE – сообщения которые не являются ошибками,
  • E_USER_DEPRECATED – сообщения о устаревшем коде.

10.10.2019, обновлено 09.10.2021

Другие публикации

HTTP коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

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.

Хостинг-провайдеры нередко отключают или блокируют вывод всех ошибок и предупреждений. Такие ограничения вводятся не просто так. Дело в том, что на рабочих серверах крайне не рекомендуется держать ошибки в открытом доступе. Информация о неисправностях может стать «наживкой» для злоумышленников.

При этом в процессе разработки сайтов и скриптов, очень важно отслеживать возникающие предупреждения. Знать о сбоях и неисправностях также важно и системным администраторам — это позволяет предотвратить проблемы на сайте или сервере.

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

В статье мы расскажем, как включить и отключить через .htaccess вывод ошибок php, а также двумя другими способами — через скрипт PHP и через файл php.ini.

Обратите внимание: в некоторых случаях изменение настроек вывода возможно только через обращение в техническую поддержку хостинга.

Через .htaccess

Перейдите в каталог сайта и откройте файл .htaccess.

Вариант 1. Чтобы включить вывод, добавьте следующие строки:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on

Чтобы отключить ошибки PHP htaccess, введите команду:

php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

Также выключить .htaccess display 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

Через логи PHP

Если вам нужно проверить или выключить ошибки только в определенных файлах, это можно сделать с помощью вызова PHP-функций.

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

А для всех типов, исключая тип Notice, так:

error_reporting(E_ALL & ~E_NOTICE)

Чтобы отключить вывод, введите команду:

Чтобы отключить логирование повторяющихся ошибок, введите:

# disable repeated error logging
php_flag ignore_repeated_errors on
php_flag ignore_repeated_source on

Вариант 2. Чтобы проверить конкретный кусок кода, подойдет команда ниже. В зависимости от типа ошибок, которые вы хотите увидеть, в скобках подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:

ini_set('display_errors', 'On')
error_reporting(E_ALL)

После этого в консоли введите:

ini_set('display_errors', 'Off')

Вариант 3. Ещё один из вариантов подключения через скрипт:

php_flag display_startup_errors on
php_flag display_errors on

Для отключения укажите:

php_flag display_startup_errors off
php_flag display_errors off

Вариант 4. Чтобы настроить вывод с логированием через конфигурацию веб-сервера, введите:

  • для Apache — ErrorLog «/var/log/apache2/my-website-error.log»,
  • для Nginx — error_log /var/log/nginx/my-website-error.log.

Подробнее о других аргументах читайте в документации на официальном сайте php.net.

Через файл php.ini

Настроить отслеживание также можно через файл php.ini. Этот вариант подойдет, когда отображение или скрытие ошибок нужно настроить для всего сайта или кода. Обратите внимание: возможность настройки через файл php.ini есть не у всех, поскольку некоторые хостинг-провайдеры частично или полностью закрывают доступ к файлу.

Вариант 1. Если у вас есть доступ, включить вывод можно командой:

После этого нужно перезагрузить сервер:

sudo apachectl -k graceful

Вариант 2. Чтобы включить вывод, используйте команду error_reporting. В зависимости от типа ошибок, которые вы хотите увидеть, после знака = подставьте нужное значение. Например, команда для вывода всех ошибок будет выглядеть так:

error_reporting = E_ALL

display_errors On

После ввода перезагрузите сервер:

sudo apachectl -k graceful

Чтобы скрыть отображение, во второй строке команды укажите Оff вместо On:

Теперь вы знаете, как настроить не только через PHP и php.ini, но и через htaccess отображение ошибок.

За уровень обработки ошибок в PHP отвечает директива error_reporting конфигурационного файла php.ini. Данный параметр определяет типы ошибок, о которых PHP информирует выводом текстового сообщения в окно браузера.

Возможные значения директивы

Уровень ошибки Константа Описание ошибки
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 Уведомления пользователей
E_ALL Все ошибки

Вышеуказанные значения (цифровые или символьные) используются для построения битовой маски, которая специфицирует выводимое сообщение об ошибке. Вы можете использовать битовые операции для маскирования определённых типов ошибок. Обратите внимание, что только ‘|’, ‘~’, ‘!’ и ‘&’ будут понятны в php.ini и что никакие битовые операции не будут понятны в php3.ini.

В PHP 4 значением по умолчанию для error_reporting будет E_ALL & ~E_NOTICE, что означает отображение всех ошибок и предупреждений, которые не имеют уровень E_NOTICE-level. В PHP 3 значение по умолчанию — E_ERROR | E_WARNING | E_PARSE означает то же самое.

Заметьте, однако, что, поскольку константы не поддерживаются в PHP 3 в файле php3.ini, установка error_reporting должна выполняться цифрами; то есть 7 по умолчанию.

Настройка при помощи php.ini

Параметр error_reporting позволяет устанавливать несколько уровней, используя побитовые флаги. К примеру, уровень:

error_reporting = E_ALL & ~E_NOTICE

позволяет выводить все ошибки, за исключением замечаний.

А для того чтобы показывать только ошибки (исключая предупреждения и замечания), директива должна быть настроена так, как показано ниже:

error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR

Настройка при помощи .htaccess

Включаем вывод ошибок в окно браузера и устанавливаем нужный уровень.

<br />
php_flag display_errors On<br />
php_value error_reporting E_ALL<br />

Настройка при помощи PHP

Включаем вывод ошибок в окно браузера и устанавливаем нужный уровень.

<?php
error_reporting(E_ALL);
ini_set("display_error", true);
ini_set("error_reporting", E_ALL);
?>

Ссылки

  • Функция error_reporting
  • Директива error_reporting файла php.ini

PHP Документация

Понравилась статья? Поделить с друзьями:
  • Error reporting e all e notice php
  • Error reporting client launcher
  • Error reporting bitrix
  • Error reporting 22527 php
  • Error reporting 22519