Error reporting e error e parse

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

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

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

Описание

error_reporting(?int $error_level = null): int

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

error_level

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

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

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

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

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

Версия Описание
8.0.0 error_level теперь допускает значение null.

Примеры

Пример #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);?>

Примечания

Подсказка

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

info at hephoz dot de

14 years ago


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

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

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

- execute this file instead of the faulty script file

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


dave at davidhbrown dot us

16 years ago


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

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

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

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


jcastromail at yahoo dot es

2 years ago


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

For example

<?php

$a

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


Fernando Piancastelli

18 years ago


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

display_errors = On
error_reporting = ~E_ALL

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


lhenry at lhenry dot com

3 years ago


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

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

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

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


ecervetti at orupaca dot fr

13 years ago


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

luisdev

4 years ago


This article refers to these two reporting levels:

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

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

What is the difference between those two levels?

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


qeremy ! gmail

7 years ago


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

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


Rash

8 years ago


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

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


chris at ocproducts dot com

6 years ago


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

keithm at aoeex dot com

12 years ago


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

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

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

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

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

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


kevinson112 at yahoo dot com

4 years ago


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

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

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


adam at adamhahn dot com

5 years ago


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

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


vdephily at bluemetrix dot com

17 years ago


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

fredrik at demomusic dot nu

17 years ago


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

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

Use the table above or:

<?php

ini_set
("error_reporting", E_YOUR_ERROR_LEVEL);

echo
ini_get("error_reporting");

?>



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

php_admin_value error_reporting YOUR_INT

in httpd.conf

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

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


rojaro at gmail dot com

12 years ago


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

<?php error_reporting(-1); ?>


j dot schriver at vindiou dot com

22 years ago


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

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

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

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

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

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

-zak@php.net]


kc8yds at gmail dot com

14 years ago


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

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

if anyone sees any problems with it please correct this post

<?php

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

?>


misplacedme at gmail dot com

13 years ago


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

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

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


Alex

16 years ago


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

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

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

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

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


teynon1 at gmail dot com

10 years ago


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

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

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

  function

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

  require

"this file does not exist";
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

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


Daz Williams (The Northeast)

13 years ago


Only display php errors to the developer...

<?php

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

{

 
ini_set('display_errors','On');

}

else

{

 
ini_set('display_errors','Off');

}

?>



Just replace 00.00.00.00 with your ip address.


forcemdt

9 years ago


Php >5.4

Creating a Custom Error Handler

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


huhiko334 at yandex dot ru

4 years ago


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

DarkGool

17 years ago


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

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

if you are not have access to php.ini file

<?php

$bit
= ini_get('error_reporting');

while (
$bit > 0) {

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

       
$end = $i;

    }

   
$res[] = $end;

   
$bit = $bit - $end;

}

?>



In $res you will have all constants of error reporting

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

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

...


&IT

2 years ago


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

error_reporting

(PHP 4, PHP 5, PHP 7)

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

Описание

int error_reporting
([ int $level
] )

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

level

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

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

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

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

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

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

Примеры

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


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

Примечания

Внимание

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

Подсказка

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

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

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

Антон Шевчук // Web-разработчик

Не совершает ошибок только тот, кто ничего не делает, и мы тому пример – трудимся не покладая рук над созданием рабочих мест для тестировщиков :)

О да, в этой статье я поведу свой рассказа об ошибках в PHP, и том как их обуздать.

Ошибки

Разновидности в семействе ошибок

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

Чтобы ни одна ошибка не ушла незамеченной потребуется включить отслеживание всех ошибок с помощью функции error_reporting(), а с помощью директивы display_errors включить их отображение:

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

Фатальные ошибки

Самый грозный вид ошибок – фатальные, они могут возникнуть как при компиляции, так и при работе парсера или PHP-скрипта, выполнение скрипта при этом прерывается.

E_PARSE
Это ошибка появляется, когда вы допускаете грубую ошибку синтаксиса и интерпретатор PHP не понимает, что вы от него хотите, например если не закрыли фигурную или круглую скобочку:

<?php
/**
 Parse error: syntax error, unexpected end of file
 */
{

Или написали на непонятном языке:

<?php
/**
 Parse error: syntax error, unexpected '...' (T_STRING)
 */
Тут будет ошибка парсера

Лишние скобочки тоже встречаются, и не важно круглые либо фигурные:

<?php
/**
 Parse error: syntax error, unexpected '}'
 */
}

Отмечу один важный момент – код файла, в котором вы допустили parse error не будет выполнен, следовательно, если вы попытаетесь включить отображение ошибок в том же файле, где возникла ошибка парсера то это не сработает:

<?php
// этот код не сработает
error_reporting(E_ALL);
ini_set('display_errors', 1);

// т.к. вот тут
ошибка парсера

E_ERROR
Это ошибка появляется, когда PHP понял что вы хотите, но сделать сие не получилось ввиду ряда причин, так же прерывает выполнение скрипта, при этом код до появления ошибки сработает:

Не был найден подключаемый файл:

/**
 Fatal error: require_once(): Failed opening required 'not-exists.php' (include_path='.:/usr/share/php:/usr/share/pear')
 */
require_once 'not-exists.php';

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

/**
 Fatal error: Uncaught exception 'Exception'
 */
throw new Exception();

При попытке вызвать несуществующий метод класса:

/**
 Fatal error: Call to undefined method stdClass::notExists()
 */
$stdClass = new stdClass();
$stdClass->notExists();

Отсутствия свободной памяти (больше, чем прописано в директиве memory_limit) или ещё чего-нить подобного:

/**
 Fatal Error: Allowed Memory Size
 */
$arr = array();

while (true) {
    $arr[] = str_pad(' ', 1024);
}

Очень часто происходит при чтении либо загрузки больших файлов, так что будьте внимательны с вопросом потребляемой памяти

Рекурсивный вызов функции. В данном примере он закончился на 256-ой итерации, ибо так прописано в настройках xdebug:

/**
 Fatal error: Maximum function nesting level of '256' reached, aborting!
 */
function deep() {
    deep();
}
deep();

Не фатальные

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

E_WARNING
Частенько встречается, когда подключаешь файл с использованием include, а его не оказывается на сервере или ошиблись указывая путь к файлу:

/**
 Warning: include_once(): Failed opening 'not-exists.php' for inclusion
 */
include_once 'not-exists.php';

Бывает, если используешь неправильный тип аргументов при вызове функций:

/**
 Warning: join(): Invalid arguments passed
 */
join('string', 'string');

Их очень много, и перечислять все не имеет смысла…

E_NOTICE
Это самые распространенные ошибки, мало того, есть любители отключать вывод ошибок и клепают их целыми днями. Возникают при целом ряде тривиальных ошибок.

Когда обращаются к неопределенной переменной:

/**
 Notice: Undefined variable: a
 */
echo $a;

Когда обращаются к несуществующему элементу массива:

<?php
/**
 Notice: Undefined index: a
 */
$b = array();
$b['a'];

Когда обращаются к несуществующей константе:

/**
 Notice: Use of undefined constant UNKNOWN_CONSTANT - assumed 'UNKNOWN_CONSTANT'
 */
echo UNKNOWN_CONSTANT;

Когда не конвертируют типы данных:

/**
 Notice: Array to string conversion
 */
echo array();

Для избежания подобных ошибок – будьте внимательней, и если вам IDE подсказывает о чём-то – не игнорируйте её:

PHP E_NOTICE in PHPStorm

E_STRICT
Это ошибки, которые научат вас писать код правильно, чтобы не было стыдно, тем более IDE вам эти ошибки сразу показывают. Вот например, если вызвали не статический метод как статику, то код будет работать, но это как-то неправильно, и возможно появление серьёзных ошибок, если в дальнейшем метод класса будет изменён, и появится обращение к $this:

/**
 Strict standards: Non-static method Strict::test() should not be called statically
 */
class Strict { 
    public function test() { 
        echo 'Test'; 
    } 
}

Strict::test();

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

/**
 Deprecated: Function split() is deprecated
 */

// популярная функция, всё никак не удалят из PHP
// deprecated since 5.3
split(',', 'a,b');

В моём редакторе подобные функции будут зачёркнуты:

PHP E_DEPRECATED in PHPStorm

Обрабатываемые

Этот вид, которые разводит сам разработчик кода, я их уже давно не встречал, не рекомендую их вам заводить:

  • E_USER_ERROR – критическая ошибка
  • E_USER_WARNING – не критическая ошибка
  • E_USER_NOTICE – сообщения которые не являются ошибками

Отдельно стоит отметить E_USER_DEPRECATED – этот вид всё ещё используется очень часто для того, чтобы напомнить программисту, что метод или функция устарели и пора переписать код без использования оной. Для создания этой и подобных ошибок используется функция trigger_error():

/**
 * @deprecated Deprecated since version 1.2, to be removed in 2.0
 */
function generateToken() {
    trigger_error('Function `generateToken` is deprecated, use class `Token` instead', E_USER_DEPRECATED);
    // ...
    // code ...
    // ...
}

Теперь, когда вы познакомились с большинством видов и типов ошибок, пора озвучить небольшое пояснение по работе директивы display_errors:

  • если display_errors = on, то в случае ошибки браузер получит html c текстом ошибки и кодом 200
  • если же display_errors = off, то для фатальных ошибок код ответа будет 500 и результат не будет возвращён пользователю, для остальных ошибок – код будет работать неправильно, но никому об этом не расскажет

Приручение

Для работы с ошибками в PHP существует 3 функции:

  • set_error_handler() — устанавливает обработчик для ошибок, которые не обрывают работу скрипта (т.е. для не фатальных ошибок)
  • error_get_last() — получает информацию о последней ошибке
  • register_shutdown_function() — регистрирует обработчик который будет запущен при завершении работы скрипта. Данная функция не относится непосредственно к обработчикам ошибок, но зачастую используется именно для этого

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

  • $errno – первый аргумент содержит тип ошибки в виде целого числа
  • $errstr – второй аргумент содержит сообщение об ошибке
  • $errfile – необязательный третий аргумент содержит имя файла, в котором произошла ошибка
  • $errline – необязательный четвертый аргумент содержит номер строки, в которой произошла ошибка
  • $errcontext – необязательный пятый аргумент содержит массив всех переменных, существующих в области видимости, где произошла ошибка

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

<?php
    // включаем отображение всех ошибок, кроме E_NOTICE
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set('display_errors', 1);
    
    // наш обработчик ошибок
    function myHandler($level, $message, $file, $line, $context) {
        // в зависимости от типа ошибки формируем заголовок сообщения
        switch ($level) {
            case E_WARNING:
                $type = 'Warning';
                break;
            case E_NOTICE:
                $type = 'Notice';
                break;
            default;
                // это не E_WARNING и не E_NOTICE
                // значит мы прекращаем обработку ошибки
                // далее обработка ложится на сам PHP
                return false;
        }
        // выводим текст ошибки
        echo "<h2>$type: $message</h2>";
        echo "<p><strong>File</strong>: $file:$line</p>";
        echo "<p><strong>Context</strong>: $". join(', $', array_keys($context))."</p>";
        // сообщаем, что мы обработали ошибку, и дальнейшая обработка не требуется
        return true;
    }
    
    // регистрируем наш обработчик, он будет срабатывать на для всех типов ошибок
    set_error_handler('myHandler', E_ALL);

У вас не получится назначить более одной функции для обработки ошибок, хотя очень бы хотелось регистрировать для каждого типа ошибок свой обработчик, но нет – пишите один обработчик, и всю логику отображения для каждого типа описывайте уже непосредственно в нём

С обработчиком, который написан выше есть одна существенная проблема – он не ловит фатальные ошибки, и вместо сайта пользователи увидят лишь пустую страницу, либо, что ещё хуже, сообщение об ошибке. Дабы не допустить подобного сценария следует воспользоваться функцией register_shutdown_function() и с её помощью зарегистрировать функцию, которая всегда будет выполняться по окончанию работы скрипта:

function shutdown() {
    echo 'Этот текст будет всегда отображаться';
}
register_shutdown_function('shutdown');

Данная функция будет срабатывать всегда!

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

function shutdown() {
    $error = error_get_last();
    if (
        // если в коде была допущена ошибка
        is_array($error) &&
        // и это одна из фатальных ошибок
        in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])
    ) {
        // очищаем буфер вывода (о нём мы ещё поговорим в последующих статьях)
        while (ob_get_level()) {
            ob_end_clean();
        }
        // выводим описание проблемы
        echo 'Сервер находится на техническом обслуживании, зайдите позже';
    }
}
register_shutdown_function('shutdown');

Задание
Дополнить обработчик фатальных ошибок выводом исходного кода файла где была допущена ошибка, а так же добавьте подсветку синтаксиса выводимого кода.

О прожорливости

Проведём простой тест, и выясним – сколько драгоценных ресурсов кушает самая тривиальная ошибка:

/**
 * Этот код не вызывает ошибок
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$a] = $i;
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

В результате запуска данного скрипта у меня получился вот такой результат:

0.002867 seconds 
984 bytes

Теперь добавим ошибку в цикле:

/**
 * Этот код содержит ошибку
 */

// сохраняем параметры памяти и времени выполнения скрипта
$memory = memory_get_usage();
$time= microtime(true);

$a = '';
$arr = [];
for ($i = 0; $i < 10000; $i++) {
    $arr[$b] = $i; // тут ошиблись с именем переменной
}

printf('%f seconds <br/>', microtime(true) - $time);
echo number_format(memory_get_usage() - $memory, 0, '.', ' '), ' bytes<br/>';

Результат ожидаемо хуже, и на порядок (даже на два порядка!):

0.263645 seconds 
992 bytes

Вывод однозначен – ошибки в коде приводят к лишней прожорливости скриптов – так что во время разработки и тестирования приложения включайте отображение всех ошибок!

Тестирование проводил на PHP версии 5.6, в седьмой версии результат лучше – 0.0004 секунды против 0.0050 – разница только на один порядок, но в любом случае результат стоит прикладываемых усилий по исправлению ошибок

Где собака зарыта

В PHP есть спец символ «@» – оператор подавления ошибок, его используют дабы не писать обработку ошибок, а положится на корректное поведение PHP в случае чего:

<?php
    echo @UNKNOWN_CONSTANT;

При этом обработчик ошибок указанный в set_error_handler() всё равно будет вызван, а факт того, что к ошибке было применено подавление можно отследить вызвав функцию error_reporting() внутри обработчика, в этом случае она вернёт 0.

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

Исключения

В эру PHP4 не было исключений (exceptions), всё было намного сложнее, и разработчики боролись с ошибками как могли, это было сражение не на жизнь, а на смерть… Окунуться в эту увлекательную историю противостояния можете в статье Исключительный код. Часть 1. Стоит ли её читать сейчас? Думаю да, ведь это поможет вам понять эволюцию языка, и раскроет всю прелесть исключений

Исключения — исключительные событие в PHP, в отличии от ошибок не просто констатируют наличие проблемы, а требуют от программиста дополнительных действий по обработке каждого конкретного случая.

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

Исключение – это объект который наследуется от класса Exception, содержит текст ошибки, статус, а также может содержать ссылку на другое исключение которое стало первопричиной данного. Модель исключений в PHP схожа с используемыми в других языках программирования. Исключение можно инициировать (как говорят, “бросить”) при помощи оператора throw, и можно перехватить (“поймать”) оператором catch. Код генерирующий исключение, должен быть окружен блоком try, для того чтобы можно было перехватить исключение. Каждый блок try должен иметь как минимум один соответствующий ему блок catch или finally:

try {
    // код который может выбросить исключение
    if (rand(0, 1)) {
        throw new Exception('One')
    } else {
        echo 'Zero';
    }
} catch (Exception $e) {
    // код который может обработать исключение
    echo $e->getMessage();
}

В каких случаях стоит применять исключения:

  • если в рамках одного метода/функции происходит несколько операций которые могут завершиться неудачей
  • если используемый вами фреймверк или библиотека декларируют их использование

Для иллюстрации первого сценария возьмём уже озвученный пример функции для записи данных в файл – помешать нам может очень много факторов, а для того, чтобы сообщить выше стоящему коду в чем именно была проблема необходимо создать и выбросить исключение:

$directory = __DIR__ . DIRECTORY_SEPARATOR . 'logs';

// директории может не быть
if (!is_dir($directory)) {
    throw new Exception('Directory `logs` is not exists');
}

// может не быть прав на запись в директорию
if (!is_writable($directory)) {
    throw new Exception('Directory `logs` is not writable');
}

// возможно кто-то уже создал файл, и закрыл к нему доступ
if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
    throw new Exception('System can't create log file');
}

fputs($file, date('[H:i:s]') . " donen");
fclose($file);

Соответственно ловить данные исключения будем примерно так:

try {
    // код который пишет в файл
    // ...
} catch (Exception $e) {
    // выводим текст ошибки
    echo 'Не получилось: '. $e->getMessage();
}

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

// исключения файловой системы
class FileSystemException extends Exception {}

// исключения связанные с директориями
class DirectoryException extends FileSystemException {
    // коды исключений
    const DIRECTORY_NOT_EXISTS =  1;
    const DIRECTORY_NOT_WRITABLE = 2;
}

// исключения связанные с файлами
class FileException extends FileSystemException {}

Теперь, если использовать эти исключения то можно получить следующий код:

try {
    // код который пишет в файл
    if (!is_dir($directory)) {
        throw new DirectoryException('Directory `logs` is not exists', DirectoryException::DIRECTORY_NOT_EXISTS);
    }

    if (!is_writable($directory)) {
        throw new DirectoryException('Directory `logs` is not writable', DirectoryException::DIRECTORY_NOT_WRITABLE);
    }

    if (!$file = @fopen($directory . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log', 'a+')) {
        throw new FileException('System can't open log file');
    }

    fputs($file, date('[H:i:s]'') . " donen");
    fclose($file);
} catch (DirectoryException $e) {
    echo 'С директорией возникла проблема: '. $e->getMessage();
} catch (FileException $e) {
    echo 'С файлом возникла проблема: '. $e->getMessage();
} catch (FileSystemException $e) {
    echo 'Ошибка файловой системы: '. $e->getMessage();
} catch (Exception $e) {
    echo 'Ошибка сервера: '. $e->getMessage();
}

Важно помнить, что Exception — это прежде всего исключительное событие, иными словами исключение из правил. Не нужно использовать их для обработки очевидных ошибок, к примеру, для валидации введённых пользователем данных (хотя тут не всё так однозначно). При этом обработчик исключений должен быть написан в том месте, где он будет способен его обработать. К примеру, обработчик для исключений вызванных недоступностью файла для записи должен быть в методе, который отвечает за выбор файла или методе его вызывающем, для того что бы он имел возможность выбрать другой файл или другую директорию.

Так, а что будет если не поймать исключение? Вы получите “Fatal Error: Uncaught exception …”. Неприятно.
Чтобы избежать подобной ситуации следует использовать функцию set_exception_handler() и установить обработчик для исключений, которые брошены вне блока try-catch и не были обработаны. После вызова такого обработчика выполнение скрипта будет остановлено:

// в качестве обработчика событий 
// будем использовать анонимную функцию
set_exception_handler(function($exception) {
    /** @var Exception $exception */
    echo $exception->getMessage(), "<br/>n";
    echo $exception->getFile(), ':', $exception->getLine(), "<br/>n";
    echo $exception->getTraceAsString(), "<br/>n";
});

Ещё расскажу про конструкцию с использованием блока finally – этот блок будет выполнен вне зависимости от того, было выброшено исключение или нет:

try {
    // код который может выбросить исключение
} catch (Exception $e) {
    // код который может обработать исключение
    // если конечно оно появится
} finally {
    // код, который будет выполнен при любом раскладе
}

Для понимания того, что это нам даёт приведу следующий пример использования блока finally:

try {
    // где-то глубоко внутри кода
    // соединение с базой данных
    $handler = mysqli_connect('localhost', 'root', '', 'test');

    try {
        // при работе с БД возникла исключительная ситуация
        // ...
        throw new Exception('DB error');
    } catch (Exception $e) {
        // исключение поймали, обработали на своём уровне
        // и должны его пробросить вверх, для дальнейшей обработки
        throw new Exception('Catch exception', 0, $e);
    } finally {
        // но, соединение с БД необходимо закрыть
        // будем делать это в блоке finally
        mysqli_close($handler);
    }

    // этот код не будет выполнен, если произойдёт исключение в коде выше
    echo "Ok";
} catch (Exception $e) {
    // ловим исключение, и выводим текст
    echo $e->getMessage();
    echo "<br/>";
    // выводим информацию о первоначальном исключении
    echo $e->getPrevious()->getMessage();
}

Т.е. запомните – блок finally будет выполнен даже в том случае, если вы в блоке catch пробрасываете исключение выше (собственно именно так он и задумывался).

Для вводной статьи информации в самый раз, кто жаждет ещё подробностей, то вы их найдёте в статье Исключительный код ;)

Задание
Написать свой обработчик исключений, с выводом текста файла где произошла ошибка, и всё это с подсветкой синтаксиса, так же не забудьте вывести trace в читаемом виде. Для ориентира – посмотрите как это круто выглядит у whoops.

PHP7 – всё не так, как было раньше

Так, вот вы сейчас всю информацию выше усвоили и теперь я буду грузить вас нововведениями в PHP7, т.е. я буду рассказывать о том, с чем вы столкнётесь через год работы PHP разработчиком. Ранее я вам рассказывал и показывал на примерах какой костыль нужно соорудить, чтобы отлавливать критические ошибки, так вот – в PHP7 это решили исправить, но как обычно завязались на обратную совместимость кода, и получили хоть и универсальное решение, но оно далеко от идеала. А теперь по пунктам об изменениях:

  1. при возникновении фатальных ошибок типа E_ERROR или фатальных ошибок с возможностью обработки E_RECOVERABLE_ERROR PHP выбрасывает исключение
  2. эти исключения не наследуют класс Exception (помните я говорил об обратной совместимости, это всё ради неё)
  3. эти исключения наследуют класс Error
  4. оба класса Exception и Error реализуют интерфейс Throwable
  5. вы не можете реализовать интерфейс Throwable в своём коде

Интерфейс Throwable практически полностью повторяет нам Exception:

interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

Сложно? Теперь на примерах, возьмём те, что были выше и слегка модернизируем:

try {
    // файл, который вызывает ошибку парсера
    include 'e_parse_include.php';
} catch (Error $e) {
    var_dump($e);
}

В результате ошибку поймаем и выведем:

object(ParseError)#1 (7) {
  ["message":protected] => string(48) "syntax error, unexpected 'будет' (T_STRING)"
  ["string":"Error":private] => string(0) ""
  ["code":protected] => int(0)
  ["file":protected] => string(49) "/www/education/error/e_parse_include.php"
  ["line":protected] => int(4)
  ["trace":"Error":private] => array(0) { }
  ["previous":"Error":private] => NULL
}

Как видите – поймали исключение ParseError, которое является наследником исключения Error, который реализует интерфейс Throwable, в доме который построил Джек. Ещё есть другие, но не буду мучать – для наглядности приведу иерархию исключений:

interface Throwable
  |- Exception implements Throwable
  |    |- ErrorException extends Exception
  |    |- ... extends Exception
  |    `- ... extends Exception
  `- Error implements Throwable
      |- TypeError extends Error
      |- ParseError extends Error
      |- ArithmeticError extends Error
      |  `- DivisionByZeroError extends ArithmeticError
      `- AssertionError extends Error 

TypeError – для ошибок, когда тип аргументов функции не совпадает с передаваемым типом:

try {
    (function(int $one, int $two) {
        return;
    })('one', 'two');
} catch (TypeError $e) {
    echo $e->getMessage();
}

ArithmeticError – могут возникнуть при математических операциях, к примеру когда результат вычисления превышает лимит выделенный для целого числа:

try {
    1 << -1;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

DivisionByZeroError – ошибка деления на ноль:

try {
    1 / 0;
} catch (ArithmeticError $e) {
    echo $e->getMessage();
}

AssertionError – редкий зверь, появляется когда условие заданное в assert() не выполняется:

ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);

try {
    assert(1 === 0);
} catch (AssertionError $e) {
    echo $e->getMessage();
}

При настройках production-серверов, директивы zend.assertions и assert.exception отключают, и это правильно

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

При написании данного раздела были использованы материалы из статьи Throwable Exceptions and Errors in PHP 7

Отладка

Иногда для отладки кода нужно отследить что происходило с переменной или объектом на определённом этапе, для этих целей есть функция debug_backtrace() и debug_print_backtrace() которые вернут историю вызовов функций/методов в обратном порядке:

<?php
function example() {
    echo '<pre>';
    debug_print_backtrace();
    echo '</pre>';
}

class ExampleClass {
    public static function method () {
        example();
    }
}

ExampleClass::method();

В результате выполнения функции debug_print_backtrace() будет выведен список вызовов приведших нас к данной точке:

#0  example() called at [/www/education/error/backtrace.php:10]
#1  ExampleClass::method() called at [/www/education/error/backtrace.php:14]

Проверить код на наличие синтаксических ошибок можно с помощью функции php_check_syntax() или же команды php -l [путь к файлу], но я не встречал использования оных.

Assert

Отдельно хочу рассказать о таком экзотическом звере как assert() в PHP, собственно это кусочек контрактной методологии программирования, и дальше я расскажу вам как я никогда его не использовал :)

Первый случай – это когда вам надо написать TODO прямо в коде, да так, чтобы точно не забыть реализовать заданный функционал:

// включаем вывод ошибок
error_reporting(E_ALL);
ini_set('display_errors', 1);

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);

assert(false, "Remove it!");

В результате выполнения данного кода получим E_WARNING:

Warning: assert(): Remove it! failed

PHP7 можно переключить в режим exception, и вместо ошибки будет всегда появляться исключение AssertionError:

// включаем asserts
ini_set('zend.assertions', 1);
ini_set('assert.active', 1);
// переключаем на исключения
ini_set('assert.exception', 1);

assert(false, "Remove it!");

В результате ожидаемо получаем не пойманный AssertionError. При необходимости, можно выбрасывать произвольное исключение:

assert(false, new Exception("Remove it!"));

Но я бы рекомендовал использовать метки @TODO, современные IDE отлично с ними работают, и вам не нужно будет прикладывать дополнительные усилия и ресурсы для работы с ними

Второй вариант использования – это создание некоего подобия TDD, но помните – это лишь подобие. Хотя, если сильно постараться, то можно получить забавный результат, который поможет в тестировании вашего кода:

// callback-функция для вывода информации в браузер
function backlog($script, $line, $code, $message) {
    echo "<h3>$message</h3>";
    highlight_string ($code);
}

// устанавливаем callback-функцию
assert_options(ASSERT_CALLBACK, 'backlog');
// отключаем вывод предупреждений
assert_options(ASSERT_WARNING,  false);

// пишем проверку и её описание
assert("sqr(4) == 16", "When I send integer, function should return square of it");

// функция, которую проверяем
function sqr($a) {
    return; // она не работает
}

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

/**
 * Настройки соединения должны передаваться в следующем виде
 *
 *     [
 *         'host' => 'localhost',
 *         'port' => 3306,
 *         'name' => 'dbname',
 *         'user' => 'root',
 *         'pass' => ''
 *     ]
 *
 * @param $settings
 */
function setupDb ($settings) {
    // проверяем настройки
    assert(isset($settings['host']), 'Db `host` is required');
    assert(isset($settings['port']) && is_int($settings['port']), 'Db `port` is required, should be integer');
    assert(isset($settings['name']), 'Db `name` is required, should be integer');

    // соединяем с БД
    // ...
}

setupDb(['host' => 'localhost']);

Никогда не используйте assert() для проверки входных параметров, ведь фактически assert() интерпретирует строковую переменную (ведёт себя как eval()), а это чревато PHP-инъекцией. И да, это правильное поведение, т.к. просто отключив assert’ы всё что передаётся внутрь будет проигнорировано, а если делать как в примере выше, то код будет выполняться, а внутрь отключенного assert’a будет передан булевый результат выполнения

Если у вас есть живой опыт использования assert() – поделитесь со мной, буду благодарен. И да, вот вам ещё занимательно чтива по этой теме – PHP Assertions, с таким же вопросом в конце :)

В заключение

Я за вас напишу выводы из данной статьи:

  • Ошибкам бой – их не должно быть в вашем коде
  • Используйте исключения – работу с ними нужно правильно организовать и будет счастье
  • Assert – узнали о них, и хорошо

P.S. Спасибо Максиму Слесаренко за помощь в написании статьи

 on
May 06, 2021

The Essential Guide to PHP Error Logging

PHP has been one of the top (if not best) server-side scripting languages in the world for decades. However, let’s be honest – error logging in PHP is not the most straightforward or intuitive. It involves tweaking a few configuration options plus some playing around to get used to. Once you have everything set up and figured out (like you will after reading this post), things seem much easier, and you realize how helpful error logging can turn out to be for your application – from debugging and troubleshooting to monitoring and maintenance. 

And this is why we are covering error logging in PHP in this post. We will start by revisiting the importance of logging errors in your application. We will then explore errors in PHP – their different types, and how they can be output. Next, we will look at all the error logging configurations in PHP, and understand how we can tweak these to our liking, before we see some error logging examples, and explore functions in PHP that allow us to write errors to log files. This post is a complete guide to error logging in PHP.

Here’s an outline of what we’ll be covering so you can easily navigate or skip ahead in the guide: 

  • Importance of Logging Errors 
  • PHP Error Types
  • Where Can PHP Errors be Output
  • Enabling and Configuring Error Reporting in PHP 
  • Logging Errors in PHP 
  • PHP’s Error Logging Functions 
    • error_log()
    • trigger_error()
    • syslog()
    • set_error_handler()
  • Popular PHP Logging Libraries 

Importance of Logging Errors 

Errors in software systems have this terrible reputation of being associated with failing things and breaking functionality. As a result, many of us often fail to recognize the importance of these loud red strings that bring our attention to faults, inconsistencies, and inaccuracies in our code – mistakes that can cost us dearly if allowed to fall through the cracks. Therefore, it is worthwhile for some of us to change our outlook towards error messages – to track, log, and organize them – and embrace their importance. 

There’s a reason developers and organizations build and leverage dedicated logging systems that keep track of errors that arise throughout an application’s lifecycle. These logs provide useful information about what went wrong, when, where, and how it can be fixed. 

For small-scale personal projects, it is common for developers not to feel the need to spend time setting up an effective logging system. This seems plausible because your code and end-user interactions are much more manageable for smaller projects. However, the requirement for effectively logging and maintaining errors and other information grows exponentially as your application scales. For larger applications, catering to thousands of users, it becomes unwieldy to track errors and updates across hundreds of components in real-time. Putting in place a system that can record the status of the very many events that an application’s operation entails allows organizations to maintain a clear record of their performance. This allows for more transparency and therefore ensures that no issues go unnoticed. As a result, this makes your application more reliable, easy to maintain, monitor, and debug.

Now that we are hopefully convinced that error logging is a worthwhile expedition, let us look at the different types of errors in PHP.

PHP Error Types

Broadly, there are five types of errors in PHP:

1. Fatal run-time Errors (E_ERROR) 

These errors typically happen when an operation in your code cannot be performed. This leads to your code exiting. An example of a fatal error would be when you call a function that hasn’t been defined in your code, shown below:

<?php
function foo() {
  echo "Function foo called.";
}
boo(); // undefined function 'boo'
?>

Error output –>

Fatal error: Uncaught Error: Call to undefined function boo() in code/my-php/index.php:5 Stack trace: #0 {main} thrown in code/my-php/index.php on line 5.

2. Warning Errors (E_WARNING)

A warning error is more gentle and less obtrusive in that it does not halt the execution. It presents a friendly reminder of something amiss in your code – a mistake that might not fail things immediately or fail anything at all but suggests a more accurate way of doing things that make your code more foolproof. These warnings can also save developers from issues that might pose a much bigger threat in the future. An example of a warning error would be when you try to include a file in PHP using an incorrect file path, as shown below:

<?php
include('filename.txt'); // arbitrary file that is not present
echo "Hello world";
?>

Error output ->

Warning: include(filename.txt): failed to open stream: No such file or directory in code/my-php/index.php on line 2

3. Parse Errors (E_PARSE)

Parse errors are also known as syntax errors as they arise from syntactical mistakes in your code. These errors are raised during the compilation of your code, making it exit before it runs. A common example of a parse error is missing a semicolon at the end of a code statement, shown below:

<?php
echo Hello world // no quotes or semicolon used
?>

Error output ->

Parse error: syntax error, unexpected 'world' (T_STRING), expecting ',' or ';' in code/my-php/index.php on line 2.

4. Notice Errors (E_NOTICE)

Notice errors are minor errors that are encountered during run-time, and just like warning errors, do not halt the execution. They usually occur when the script is attempting to access an undefined variable, for example, as shown below:

<?php
$a = 1;
$c = $a + $b; // undefined variable $b
?>

Error output ->

Notice: Undefined variable: b in code/my-php/index.php on line 3

5. User Errors (E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE) 

User errors are user-defined, i.e., present a custom user-generated message raised explicitly from the code to capture a specific condition. These errors are manually raised by developers using the trigger_error function instead of the PHP engine. They are further classified as fatal, warning, and notice errors, but we’ll group them all as user errors for simplicity.

Where can PHP Errors be Output?

There are two primary places where we can have our errors presented in PHP – through inline errors and dedicated error log files.

Inline Errors 

Inline errors are those that show up on your webpage in the browser or your terminal via STDOUT in a command-line environment. These errors prove to be quite useful during development – for developers to debug their code, fix issues, and get information about the overall execution. Below is an example of what these errors usually look like in the browser:

undefined

Though this proves to be super helpful for developers, you should be very careful in ensuring that these errors are not output when your application goes into production – for two reasons – end-user experience and security. You can toggle the displaying of these errors using the display_error directive in your system’s configuration. We’ll dive deeper into this in the next section.

Error Log Files 

Inline errors are not persistent in memory, i.e., they are not saved anywhere and are only viewed as long as the browser or terminal session is alive. Additionally, you’ll only want to have them in a development environment. Conversely, as the theme of this post suggests, logging your errors is the more intelligent and more systematic approach towards maintaining large-scale applications. These are persistent in memory and provide information about the operation of your application across multiple components in one place, making it easier for monitoring and troubleshooting.

PHP, therefore, allows you to direct all your errors to specific log files; these files store timestamps, error stack traces, custom messages, and other helpful information about the source of the error and how to fix it. You can specify the path of your custom log file using the error_log directive of your system configuration. Here’s an example of an error log file:

undefined

You can also choose to have your errors logged to the system’s log file, usually located in – /var/log/syslog. We’ll cover this in a later section in the post.

Now let’s look at how we can configure where and how we want our errors logged.

Enabling and Configuring Error Reporting in PHP 

As we discussed previously, logging in PHP is slightly less straightforward than other languages and frameworks. You might have to tweak a few options in configuration files to customize logging patterns. For example, when you install PHP on your machine, the initial configuration comes with some aspects of error logging disabled. This differs from system to system, and therefore, you should manually check these settings before getting started.

Logging Configuration Options in php.ini File

The configuration options are in the php.ini file. This file is read when PHP starts up and allows developers to play around with PHP’s functionality. Usually, this file can be found somewhere in the /etc/php directory on most Linux systems. 

There are a bunch of directives (options) pertaining to the logging of errors in PHP that we can configure in this php.ini file:

  • display_errors (default: 1)

Display errors are the inline errors we previously looked at. This directive can be used to good effect during development to output PHP error messages to the browser or terminal. However, for applications in production, you should likely turn this off to save your users from a poor website experience due to obscure error messages. Not only that, but this also protects you from exposing valuable information about the internals of your application as a security measure.

  • display_startup_errors (default: 0)

As the name suggests, this is to output any errors that take place when PHP starts up. These usually do not provide any valuable information about your application specifically, and therefore need not be turned on.

  • log_errors (default: 0)

This directive allows you to toggle the logging of errors to the specified path (in the next directive). Because this is turned off by default, it would be advisable to toggle this to 1 for recording your application’s error messages in a log file.

  • error_log (default: 0)

This directive allows you to specify the path of your log file. You can also set this to “syslog” for directing all your error log messages to the system log. 

  • error_reporting (default: null)

The error_reporting directive allows you to customize which error levels you want reported, and which you are okay with going unreported. For example, you can use the directive as shown below to have all errors reported: error_reporting = E_ALL

  • track_errors (default: 0)

This directive allows you to access the last raised error message in the $php_errormsg global variable in your code and can keep track of errors across your whole project.

After making changes to your php.ini file, you will need to restart the server for the changes to take effect.

The ini_set() Function

However, if you are unable to locate the php.ini file, or prefer overriding your project’s global configuration options, there is also an option to update these directives using the ini_set() function in your PHP code. For example, the below code can be used for customizing error reporting in your project:

<?php

// enabling error logging
ini_set('log_errors', 1);  

// Customize reporting of errors
ini_set('error_reporting', E_WARNING | E_ERROR | E_PARSE | E_NOTICE);

// specify error log file path
ini_set('error_log', '/tmp/my-logs.log');

?>

The error_reporting() Function

One can also modify the error_reporting configuration option using the error_reporting() function from inside your code during run-time. As in the ini_set function, you can use bitwise operators like OR (|), AND (&), NOT (~), etc., when specifying the error levels to be reported. Below are a few examples of how this function can be used.

// Report only selected kinds of errors
error_reporting(E_ERROR | E_PARSE | E_NOTICE);

or

// Report all errors except E_WARNING
error_reporting(E_ALL & ~E_WARNING);

Now that we have got the system configurations and overall setup out of the way, let’s look at an example of how errors in your project code can be logged to files on your system.

Logging Errors in PHP

First, we will override the logging configuration parameters using the ini_set() function to enable error logging and specify the log file’s path. Then we’ll write some erroneous code to have PHP raise an error that we would like to have logged.

<?php
  ini_set('log_errors', 1); // enabling error logging
  ini_set('error_log', '/path/my-error-file.log'); // specifying log file path

  echo $b; // undefined variable should raise error
?>

After opening the web page on our browser, let’s open the ‘my-error-file.log’ file to see if the error message was logged. Here is the log file output:

[28-Feb-2021 13:34:36 UTC] PHP Notice:  Undefined variable: b in code/my-php/index.php on line 5

As you can see, our notice error was logged with a timestamp. As our code encounters more and more errors, this file will keep getting populated with corresponding timestamps. Note that we haven’t explicitly turned off display_errors, so these error messages are likely to be logged to the browser web page – something you might want to avoid during production. 

This was an example of capturing errors raised by PHP in log files. Now let’s look at how we can raise and log custom error messages for our application.

PHP’s Error Logging Functions

So far, we looked at errors raised by PHP – errors about your code execution. However, oftentimes you would want to also capture custom errors, with custom error messages specific to the functioning of your application. These so-called errors might not necessarily fail your code or halt its execution, but can indicate conditions characterized as erroneous and noteworthy for your application. These can act as indications to the organization about anomalous behavior that the team might want to look into and fix.

To facilitate this, PHP provides a set of functions that we can use to actively log errors in our code.

error_log()

The most common method for actively logging errors is the error_log() function. This sends a string argument for the error message to the log file.

error_log (string $message, int $message_type=0, string $destination=?, string $extra_headers=?) : bool

It also takes many other parameters to send error messages over email or specific log files. However, for the sake of simplicity, we won’t be covering that here. 

The interesting thing about this function is it logs your error message to the file specified in the configuration (or to the system log), regardless of the value of the log_errors directive. Let’s take a very simple example of logging an error when a specific condition in our code is met.

<?php

ini_set('error_log', '/path/my-error-file.log');
$a = 5;
$b = 10;

$c = $a + $b;

if ($c < 20) {
error_log("Sum is less than 20."); // logging custom error message
}

?>

Here is the output of the log file:

[28-Feb-2021 13:31:50 UTC] Sum is less than 20

Similarly, you can also log the values of variables in your code to provide additional context about your errors. Let’s see an example for that:

<?php
  ini_set('error_log', '/path/my-error-file.log');

  $languagesArray = array("PHP", "Python", "Node.js");
  error_log("Lorem ipsum. Array data -> ".print_r($languagesArray, true));
?>

Here’s the output of the log file ->

[28-Feb-2021 13:49:28 UTC] Lorem ipsum. Array data -> Array

(

   [0] => PHP

   [1] => Python

   [2] => Node.js

)

trigger_error()

The trigger_error() function can be used to raise a user-defined error/warning/notice. You can also specify the error type based on the condition. This allows you to customize its reporting and other behavior – for example, using an error type of E_USER_ERROR. We can cause the code to exit immediately compared to an E_USER_WARNING error.

trigger_error (string $error_msg, int $error_type=E_USER_NOTICE) : bool

The difference between trigger_error and error_log is that the former only generates a user error and depends on your system’s logging configurations to handle this error message (whether displayed or logged). error_log, on the other hand, will log your message regardless of the system’s configuration.

Here is the code for the same example we saw previously:

<?php
ini_set('log_errors', 1); // enabling error logging
ini_set('error_log', '/path/my-error-file.log'); // specifying log file path

$a = 5;
$b = 10;
$c = $a + $b;

if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_ERROR);
      echo "This will not be printed!";
}

?>

This adds a similar log entry to what we saw previously, but with an error level, plus the conventional error source information (log file output below):

[01-Mar-2021 01:16:56 UTC] PHP Fatal error:  Sum is less than 20. in code/my-php/index.php on line 10

syslog()

You can also choose to directly send an error message to the system’s log using the syslog() function.

syslog (int $priority, string $message) : bool

The first argument is the error’s priority level – LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_ALERT, LOG_EMERG, etc. (more about it here).  The second argument is the actual message’s text. This is how the function can be used:

<?php
// opening logger connection
openlog('myApp', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR
); // more information about params in documentation

syslog(LOG_WARNING, "My error message!");

closelog();
?>

This should reflect in your system’s logger (usually in /var/log/syslog) as:

Mar 1 13:27:15 zsh php: My error message! 

set_error_handler()

To customize the handling of all the user-defined errors throughout your code, PHP allows you to specify a custom error handler function to override the default handling of errors. This makes it easy for organizations to modify how they want their errors logged, the corresponding error messages send method, and much more. The set_error_handler() function helps with this.

set_error_handler (callable $error_handler, int $error_types=E_ALL | E_STRICT) : mixed

It takes as an argument our custom error handler function, which will define the handling of our errors, and look something like this:

handler (int $errno, string $errstr, string $errfile=?, int $errline=?, array $errcontext=?) : bool

This takes in many parameters like the error number, error string, corresponding file, etc. Let’s understand this better using the same previous example:

<?php
// custom error handler function ->
function myErrorHandler($errno, $errstr, $errfile, $errline, $errcontext){
    $message = date("Y-m-d H:i:s - "); // timestamp in error message
    $message .= "My Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, n"; // custom error message
    $message .= "Variables:" . print_r($errcontext, true) . "rn";
   
    error_log($message, 3, "/path/my-error-file.log");
    die("There was a problem, please try again."); // exit code
}

set_error_handler("myErrorHandler");

$a = 5;
$b = 10;
$c = $a + $b;

if ($c < 20) {
trigger_error("Sum is less than 20.", E_USER_WARNING);
}

echo "This will not be printed!";
?>

Here, we define a custom error handler function where we modify the error message a bit, log it, and exit the code. Then, when we use the trigger_error() function, its logging is handled by the above function, which takes care of the rest. This is what the output in the log file looks like:

2021-03-01 06:58:07 - My Error: [512], Sum is less than 20. in code/my-php/index.php on line 22,

Variables:Array

(

   [a] => 5

   [b] => 10

   [c] => 15

)

As you can see, this can be used to fully customize error logging in applications, allowing organizations to prioritize aspects of errors and contexts that are more important for their application.

Popular PHP Logging Libraries 

Thanks to the huge PHP community support on the internet, there have been very many logging libraries that aim to provide more functionality and ease the overall process for developers and organizations. Each of the renowned PHP frameworks that you must have heard of come equipped with logging libraries built-in. There are also now logging standards established, like the PSR-3 (PHP Standards Recommendation) logger interface, that defines a standardized interface to follow for logging libraries. 

Below is a list of some of the most popular logging libraries in PHP:

  • Monolog
  • Analog
  • KLogger
  • Log4PHP

Feel free to check these out to see what default error logging in PHP is missing out on.

Wrapping Up 

In this post, we covered everything about errors and logging in PHP. We discussed the importance of logging mechanisms in your application, looked at the different types of errors in PHP, and explored the various configuration options and PHP functions that we can use to log errors effectively.

Now that you have a decent understanding of everything, go ahead and start implementing error logging for your application! It doesn’t matter if you are working on a small project where things might seem under control even without log files. Logging your errors is considered one of the top “best practices” in software development that becomes exponentially more important as your applications grow and scale.

To learn more about logging in PHP in general, feel free to check out the Tutorial: Log to Console in PHP on our blog!

To up your application monitoring game by identifying bottlenecks and gaining effective application performance insights, check out ScoutAPM to get started with a 14-day free trial!

Happy coding!

За уровень обработки ошибок в 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 Документация

During the execution of a PHP application, it can generate a wide range of warnings and errors. For developers seeking to troubleshoot a misbehaving application, being able to check these errors is critical. Developers, on the other hand, frequently encounter difficulties when attempting to display errors from their PHP applications. Instead, their applications simply stop working.

First and foremost, you should be aware that with PHP, some errors prevent the script from being executed. Some errors, on the other hand, just display error messages with a warning. Then you’ll learn how to use PHP to show or hide all error reporting.

In PHP, there are four types of errors:

  1. Notice Error – When attempting to access an undefined index in a PHP code, an error occurs. The execution of the PHP code is not halted by the notice error. It just alerts you to the fact that there is an issue.
  2. Warning Error – The most common causes of warning errors are omitting a file or invoking a function with improper parameters. It’s comparable to seeing a mistake, but it doesn’t stop the PHP code from running. It just serves as a reminder that the script has a flaw.
  3. Fatal Error – When undefined functions and classes are called in a PHP code, a fatal error occurs. The PHP code is stopped and an error message is displayed when a fatal error occurs.
  4. Parse Error – When a syntax issue occurs in the script, it is referred to as a parse error. The execution of the PHP code is also stopped when a parse error occurs, and an error message is displayed.

You’ve come to the right place if you’re having troubles with your PHP web application and need to see all of the errors and warnings. We’ll go through all of the different ways to activate PHP errors and warnings in this tutorial.

  1. To Show All PHP Errors
  2. .htaccess Configuration to Show PHP Errors
  3. Enable Detailed Warnings and Notices
  4. In-depth with the error_reporting() function
  5. Use error_log() Function to Log PHP Error
  6. Use Web Server Configuration to Log PHP Errors
  7. Collect PHP Errors using Atatus

1. To Show All PHP Errors

Adding these lines to your PHP code file is the quickest way to output all PHP errors and warnings:

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

The ini_set() function will attempt to override the PHP ini file’s configuration.

The display_errors and display_startup_errors directives are just two of the options.

  1. The display_errors directive determines whether or not the errors are visible to the user. After development, the dispay_errors directive should usually be disabled.
  2. The display_startup_errors directive, on the other hand, is separate since display errors do not handle errors that occur during PHP’s startup sequence.

The official documentation contains a list of directives that can be overridden by the ini_set() function. Unfortunately, parsing problems such as missing semicolons or curly brackets will not be displayed by these two directives. The PHP ini configuration must be changed in this scenario.

To display all errors, including parsing errors, in xampp, make the following changes to the php.ini example file and restart the apache server.

display_errors = on

In the PHP.ini file, set the display errors directive to turn on. It will show all errors that can’t be seen by just calling the ini_set() function, such as syntax and parsing errors.

2. .htaccess Configuration to Show PHP Errors

The directory files are normally accessible to developers. The .htaccess file in the project’s root or public directory can also be used to enable or disable the directive for displaying PHP errors.

php_flag display_startup_errors on
php_flag display_errors on

.htaccess has directives for display_startup_errors and display_errors, similar to what will be added to the PHP code to show PHP errors. The benefit of displaying or silencing error messages in this way is that development and production can have separate .htaccess files, with production suppressing error displays.

You may want to adjust display_errors in .htaccess or your PHP.ini file depending on which files you have access to and how you handle deployments and server configurations. Many hosting companies won’t let you change the PHP.ini file to enable display errors.

3. Enable Detailed Warnings and Notices

Warnings that appear to not affect the application at first might sometimes result in fatal errors under certain circumstances. These warnings must be fixed because they indicate that the application will not function normally in certain circumstances. If these warnings result in a large number of errors, it would be more practical to hide the errors and only display the warning messages.

error_reporting(E_WARNING);

Showing warnings and hiding errors are as simple as adding a single line of code for a developer. The parameter for the error reporting function will be “E_WARNING | E_NOTICE” to display warnings and notifications. As bitwise operators, the error reporting function can accept E_ERROR, E_WARNING, E_PARSE, and E_NOTICE parameters.

For ease of reference, these constants are also detailed in the online PHP Manual.

To report all errors except notices, use the option «E_ALL & E_NOTICE,» where E_ALL refers to all of the error reporting function’s potential parameters.

4. In-depth with the error_reporting() Function

One of the first results when you browser «PHP errors» is a link to the error_reporting() function documentation.

The PHP error_reporting() function allows developers to choose which and how many errors should be displayed in their applications. Remember that this function will set the error reporting directive in the PHP ini configuration during runtime.

error_reporting(0);

The value zero should be supplied to the error_reporting() function to delete all errors, warnings, parse messages, and notices. This line of code would be impractical to include in each of the PHP files. It is preferable to disable report messages in the PHP ini file or the .htaccess file.

error_reporting(-1);

An integer value is also passed as an input to the error_reporting() function. In PHP, we may use this method to display errors. In PHP, there are many different types of errors. All PHP errors are represented by the -1 level. Even with new levels and constants, passing the value -1 will work in future PHP versions.

error_reporting(E_NOTICE);

Variables can be used even if they aren’t declared in PHP. This isn’t recommended because undeclared variables can create issues in the application when they’re utilized in loops and conditions.

This can also happen when the stated variable is spelled differently than the variable used in conditions or loops. These undeclared variables will be displayed in the web application if E_NOTICE is supplied in the error_reporting() function.

error_reporting(E_ALL & ~E_NOTICE);

You can filter which errors are displayed using the error_reporting() function. The “~” character stands for “not” or “no,” hence the parameter ~E_NOTICE indicates that notices should not be displayed.

In the code, keep an eye out for the letters «&» and «|.» The “&” symbol stands for “true for all,” whereas the “|” character stands for “true for either.” In PHP, these two characters have the same meaning: OR and AND.

5. Use error_log() Function to Log PHP Error

Error messages must not be displayed to end-users during production, but they must be logged for tracing purposes. The best approach to keep track of these error messages in a live web application is to keep track of them in log files.

The error_log() function, which accepts four parameters, provides a simple way to use log files. The first parameter, which contains information about the log errors or what should be logged, is the only one that must be provided. This function’s type, destination, and header parameters are all optional.

error_log("Whoosh!!! Something is wrong!", 0);

If the type option is not specified, it defaults to 0, which means that this log information will be appended to the web server’s log file.

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

The error logs supplied in the third parameter will be emailed using the type 1 parameter. To use this feature, the PHP ini must have a valid SMTP configuration to send emails.

Host, encryption type, username, password, and port are among the SMTP ini directives. This kind of error reporting is recommended for logging or notifying errors that must be corrected as soon as possible.

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

Type 3 must be used to log messages in a different file established by the web server’s configuration. The third parameter specifies the log file’s location, which must be writable by the webserver. The log file’s location might be either a relative or absolute library to where this code is invoked.

You can also refer to the error_log() function documentation to know more.

6. Use Web Server Configuration to Log PHP Errors

The ideal technique to record errors is to define them in the web server configuration file, rather than modifying parameters in the .htaccess or adding lines in the PHP code to show errors.

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

These files must be added to the virtual host of a specific HTML page or application in Apache, which is commonly found in the sites-available folder in Ubuntu or the httpd-vhosts file in Windows.

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

The directive is just called error_log() in Nginx, as it is in Apache. The log files for both Apache and Nginx web servers must be writable by the webserver. Fortunately, the folders for the log files of these two web servers are already writable after installation.

7. Collect PHP Errors using Atatus

Atatus is an Application Performance Management (APM) solution that collects all requests to your PHP applications without requiring you to change your source code. However, the tool does more than just keep track of your application’s performance. Atatus’ ability to automatically gather all unhandled errors in your PHP application is one of its best features.

To fix PHP exceptions, gather all necessary information such as class, message, URL, request agent, version, and so on. Every PHP error is logged and captured with a full stack trace, with the precise line of source code marked, to make bug fixes easy.

Read the guide to know more about PHP Performance Monitoring.

All errors are automatically logged and structured in Atatus so that they can be easily viewed. Not only will Atatus show you what errors have happened, but it will also examine where and why they occurred. The logs also display the time and number of occurrences, making it much easier to focus on which issue to address.

Start your 14-day free trial of Atatus, right now!!!

Summary

When there is an issue with the PHP code, a PHP error occurs. Even something as simple as incorrect syntax or forgetting a semicolon can result in an error, prompting a notification. Alternatively, the cause could be more complicated, such as invoking an incorrect variable, which can result in a fatal error and cause your system to crash.

This tutorial has shown you several ways to enable and display all PHP errors and warnings. You can boost your ability to debug PHP issues by receiving error notifications fast and precisely.

Let us know what you think about displaying PHP errors in the below comment section.

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

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

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

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

Enable the error reporting: It will enable error reporting.

ini_set("display_errors", "1") 

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

ini_set("display_errors", "0")

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

PHP

<?php

   ini_set('display_errors','1');

  function printmyname()

  {

     echo "My name is GeeksforGeeks";

  }

  printname();

?>

Output:

Fatal error: Call to undefined function printname()

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

PHP

<?php

  ini_set('display_errors','0');

  function printmyname()

  {

     echo "My name is GeeksforGeeks";

  }

  printname();

?>

Output:

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

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

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

Syntax:

error_reporting(error_names);

Parameter value:

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

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

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

PHP

<?php

    error_reporting(E_ERROR | E_WARNING);

    error_reporting(E_ALL);

    error_reporting(E_ALL & ~E_PARSE);

    error_reporting(-1);

    error_reporting(0);

    echo "Sample error reporting code using error_reporting function";

?>

Output:

Sample error reporting code using error_reporting function

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

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

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

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

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

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

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

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

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

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

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

display_errors = on

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

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

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

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

php_flag display_startup_errors on
php_flag display_errors on

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

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

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

php_value error_log logs/all_errors.log

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

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

error_reporting(E_WARNING);

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

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

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

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

error_reporting(0);

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

error_reporting(E_NOTICE);

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

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

error_reporting(E_ALL & ~E_NOTICE);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Пример для Apache:

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

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

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

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

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