Error reporting 1 not working

PHP snippet: <?php error_reporting(0); $a; echo ' a = '.$a.'
'; error_reporting(1); echo ' b= '.$b; ?> and the ouput is a = b= without any notice. I expected the

PHP snippet:

 <?php
error_reporting(0);
$a;

echo ' a = '.$a.'<br>';



error_reporting(1);

echo ' b= '.$b;

?>

and the ouput is

a =
b= 

without any notice.

I expected the error_reporting(1) to work to show errors. But if I use error_reporting(E_ALL) instead, it shows the notice for the undefined variable b;

Questions are :

1) If the parameter is 0 or false then errors are supressed, then why not 1 or true will work in the reverse way ?

2) Where is it mentioned in the documentation of PHP site that 0 or false can be passed as a parameter whereas I can find here that E_ALL can be used as a parameter ?

asked Oct 5, 2014 at 8:45

Istiaque Ahmed's user avatar

Istiaque AhmedIstiaque Ahmed

5,97922 gold badges70 silver badges140 bronze badges

error_reporting(1) is equivelant for error_reporting(E_ERROR) that means you will only activate error reporting from PHP
In your case you have to write error_reporting(E_NOTICE) to see the message from PHP
You can combine with many type of report error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE)
To re activate all type of errors and warning you can write error_reporting(-1)
Hope it helps

answered Oct 5, 2014 at 9:06

Halayem Anis's user avatar

Halayem AnisHalayem Anis

7,5862 gold badges25 silver badges44 bronze badges

1

error_reporting() expects a bit field parameter $level which represents the various error_reporting options. To enable notices about undefined variables you want the combination of E_ALL and E_STRICT:

error_reporting(E_ALL | E_STRICT);

(From PHP 5.4 you can omit E_STRICT since it is included in E_ALL). Using the integer 0 just means that you have disabled all options.

Depending on your ini settings you may also want to enable the displaying of errors — for debugging, disable it on production:

ini_set('display_errors', 1);

Example:

ini_set('display_errors', 1); 

error_reporting(0);
echo $a; 

error_reporting(E_ALL | E_STRICT);
echo $b;

The example above will display a notice when you attempt to access $b which is undefined.

answered Oct 5, 2014 at 9:02

hek2mgl's user avatar

7

This is my PHP script —

<?php
  error_reporting(E_ALL);
  echo('catch this -> ' ;. $thisdoesnotexist);
?>

Which obviously should show something if it were to be executed.

All I see is an empty page. Why is error_reporting(E_ALL) not working?

<?php
  ini_set("display_errors", "1");
  error_reporting(E_ALL);
  echo('catch this -> ' ;. $thisdoesnotexist);
?>

Does not help either. All I get is an empty page.

I’ve been to php.ini and set display_errors = On and display_startup_errors = On. Nothing happens.

Peter Mortensen's user avatar

asked Jun 5, 2013 at 7:07

Samik Sengupta's user avatar

Samik SenguptaSamik Sengupta

1,9269 gold badges30 silver badges50 bronze badges

6

Your file has a syntax error, so your file was not interpreted, so settings were not changed and you have a blank page.

You can separate your file in two:

File index.php

<?php
    ini_set("display_errors", "1");
    error_reporting(E_ALL);
    include 'error.php';

File error.php

<?
    echo('catch this -> ' ;. $thisdoesnotexist);

Peter Mortensen's user avatar

answered Jun 5, 2013 at 7:16

sectus's user avatar

1

That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn’t yet executed the error_reporting line, therefore the error reporting settings aren’t changed yet.

You cannot change error reporting settings (or really, do anything) in a file with syntax errors.

answered Jun 5, 2013 at 7:14

deceze's user avatar

decezedeceze

504k85 gold badges730 silver badges873 bronze badges

In your php.ini file check for display_errors. I think it is off.

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

answered Jun 5, 2013 at 7:15

som's user avatar

somsom

4,6302 gold badges20 silver badges36 bronze badges

2

In your php.ini file check for display_errors. If it is off, then make it on as below:

display_errors = On

It should display warnings/notices/errors.

Please read error_reporting int.

Peter Mortensen's user avatar

answered Jun 5, 2013 at 7:12

Altaf Hussain's user avatar

Altaf HussainAltaf Hussain

5,1814 gold badges30 silver badges47 bronze badges

1

You can try to put this in your php.ini:

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

In php.ini file also you can set error_reporting();.

Peter Mortensen's user avatar

answered May 17, 2018 at 9:44

Kaushal Roy's user avatar

1

Turn on display errors in your ini file:

display_errors string

Peter Mortensen's user avatar

answered Jun 5, 2013 at 7:10

exussum's user avatar

exussumexussum

18k8 gold badges31 silver badges64 bronze badges

Just do the following:

  1. Check phpinfo();. Check if display_errors is on or off

  2. If it is On, just add error_reporting(E_ALL); in your primary index file.

  3. If it is Off, just add it in your primary index file

    ini_set("display_errors", "1"); // This is the instant setup for individual applications
    error_reporting(E_ALL);

  4. then check phpinfo();. Check display_errors. Now it is on, which is only for this application

  5. then create any code error for testing and reload the page

Hurray! Now you can see the errors in your console. If the errors are not displaying in your console and the page loading failed with a red alert in network, don’t worry.

Check if you have enabled modsecurity and it has any rule checking is written in SecRule for PHP. Remove that secrule or disable the modsecurity for your development period.

Peter Mortensen's user avatar

answered Jun 4, 2021 at 12:21

Karthikeyan Ganesan's user avatar

3

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

error_reportingSets which PHP errors are reported

Description

error_reporting(?int $error_level = null): int

Parameters

error_level

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

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

Return Values

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

Changelog

Version Description
8.0.0 error_level is nullable now.

Examples

Example #1 error_reporting() examples


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

Notes

Tip

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

See Also

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

info at hephoz dot de

14 years ago


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

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

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

- execute this file instead of the faulty script file

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


dave at davidhbrown dot us

16 years ago


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

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

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

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


jcastromail at yahoo dot es

2 years ago


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

For example

<?php

$a

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


Fernando Piancastelli

18 years ago


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

display_errors = On
error_reporting = ~E_ALL

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


lhenry at lhenry dot com

3 years ago


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

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

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

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


ecervetti at orupaca dot fr

13 years ago


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

luisdev

4 years ago


This article refers to these two reporting levels:

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

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

What is the difference between those two levels?

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


qeremy ! gmail

7 years ago


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

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


Rash

8 years ago


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

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


chris at ocproducts dot com

6 years ago


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

keithm at aoeex dot com

12 years ago


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

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

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

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

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

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


kevinson112 at yahoo dot com

4 years ago


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

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

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


adam at adamhahn dot com

5 years ago


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

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


vdephily at bluemetrix dot com

17 years ago


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

fredrik at demomusic dot nu

17 years ago


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

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

Use the table above or:

<?php

ini_set
("error_reporting", E_YOUR_ERROR_LEVEL);

echo
ini_get("error_reporting");

?>



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

php_admin_value error_reporting YOUR_INT

in httpd.conf

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

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


rojaro at gmail dot com

12 years ago


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

<?php error_reporting(-1); ?>


j dot schriver at vindiou dot com

22 years ago


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

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

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

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

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

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

-zak@php.net]


kc8yds at gmail dot com

14 years ago


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

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

if anyone sees any problems with it please correct this post

<?php

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

?>


misplacedme at gmail dot com

13 years ago


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

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

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


Alex

16 years ago


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

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

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

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

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


teynon1 at gmail dot com

10 years ago


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

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

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

  function

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

  require

"this file does not exist";
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

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


Daz Williams (The Northeast)

13 years ago


Only display php errors to the developer...

<?php

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

{

 
ini_set('display_errors','On');

}

else

{

 
ini_set('display_errors','Off');

}

?>



Just replace 00.00.00.00 with your ip address.


forcemdt

9 years ago


Php >5.4

Creating a Custom Error Handler

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


huhiko334 at yandex dot ru

4 years ago


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

DarkGool

17 years ago


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

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

if you are not have access to php.ini file

<?php

$bit
= ini_get('error_reporting');

while (
$bit > 0) {

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

       
$end = $i;

    }

   
$res[] = $end;

   
$bit = $bit - $end;

}

?>



In $res you will have all constants of error reporting

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

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

...


&IT

2 years ago


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

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

За последние 24 часа нас посетили 11483 программиста и 1157 роботов. Сейчас ищут 397 программистов …


  1. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    Переехал на новый хостинг, в php.ini сейчас прописано error_reporting = 0 (в обоих, на всякий случай). Но всё-равно вижу все ошибки, даже strict. Убрал все свои скрипты и .htaccess с хостинга, создал в корне новый index.php со следующим содержимым:

    Результат его работы:

    Методом тыка выяснил, что php.ini всё-таки не игнорируется, если выставить в нем директиву display_errors на Off, то ошибки пропадают. Значит error_reporting прописано где-то ещё. Ума не приложу где оно может быть ещё прописано, прошу помощи.


  2. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    ini_set(‘display_errors’, 0); те в помощь, милчеловек. Поставь в начале скрипта.
    Али вот так — error_reporting(0); попробуй, тож в начале. Что-то да сработает, эт точно.


  3. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    display_errors меня не интересует, я хочу чтобы основные ошибки отображались.


  4. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    error_reporting(E_ALL & ~E_NOTICE);
    Все окромя нотисов как есть покажет.


  5. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

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


  6. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

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

    В index.php пропиши. Или у тебя там сервис-ориентированная архитектура, а-ля фейсбук? Один скрипт выбрасывает аяксы и они подсасывают фрагменты страницы с разных точек входа? Я б советовал гнать все изначально через какой-то один шлюз и там контроллить.

    Добавлено спустя 4 минуты 1 секунду:

    Трясти хостера на тему «хочу свой php.ini».

    Добавлено спустя 1 минуту 17 секунд:
    На хостинге, где я сижу, свой php.ini на шареде в пол пинка цепляется.
    Совершенно легально.


  7. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    У меня не хостинг, у меня VDS, php.ini редактируется, вот только error_reporting не фурычит как должен. Вот phpinfo(): http://82.146.34.188/test.php
    error_reporting показывает значение 32759. Посмотрел у себя на денвере, где стоит error_reporting = E_ALL & ~E_NOTICE, там выводится значение 30711.


  8. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    в php-fpm есть свой конфиг, в котором тоже могут указываться переменные конфига самого пхп соотв меняя их значения


  9. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    Есть такой. Действительно нашел в нем:

    Убрал, перезагрузил сервер — шиш. Вот какую хрень я вижу при попытке залогиниться: http://joxi.ru/VfJnUxjKTJAdTv3F_Sc

    Добавлено спустя 16 минут:
    Попробовал: error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT — всё-равно стрикты отображаются. Хрень какая-то.

    Добавлено спустя 45 минут 34 секунды:
    Короче… походу это не error_reporting, потому что его изменение фиксируется нормально в phpinfo(): http://82.146.34.188/test.php
    Стрикт-ошибки могут быть прописаны отдельной командой?


  10. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768


  11. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4


  12. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    внезапно error_reporting
    (ಠ‿ಠ)


  13. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    Я понял в чем дело, разница в версиях PHP. Я прохлопал тот момент, что вышла PHP 5.4, а в ней E_STRICT стала частью E_ALL. Странно почему не избавляет от стрикт-ошибок такая запись:

    1. error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT

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


  14. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    ну хз, у меня стрикты вроде не кажет, а вот про нонстатик статик вроде всегда орал в любом случае…


  15. Freakmeister

    Freakmeister
    Активный пользователь

    С нами с:
    20 дек 2009
    Сообщения:
    871
    Симпатии:
    4

    Ну так это ведь к стриктам относится, или я чего-то не понимаю? На PHP 5.3 этих ошибок не было.


  16. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768


  17. sobachnik

    У меня на 5.4.11 это вообще фаталы, а не стрикты…


  18. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

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


  19. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    статик нонстатик это вообще не тянет на нотис. это вполне себе такой фатал.


  20. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    Такой статик вызов нон-статик дает стрикт

    Добавлено спустя 1 минуту 16 секунд:
    то есть если мы работаем с объектом, а не классом, то можем все методы вызывать через ::


  21. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

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


  22. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    точняк

    1.    return ‘В статик нет $this->rand!’;


  23. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

How to Display PHP Errors and Enable Error Reporting

I still vividly remember the first time I learned about PHP error handling.

It was in my fourth year of programming, my second with PHP, and I’d applied for a developer position at a local agency. The application required me to send in a code sample (GitHub as we know it didn’t exist back then) so I zipped and sent a simple custom CMS I’d created the previous year.

The email I got back from the person reviewing the code still chills my bones to this day.

«I was a bit worried about your project, but once I turned error reporting off, I see it actually works pretty well».

That was the first time I searched «PHP error reporting», discovered how to enable it, and died inside when I saw the stream of errors that were hidden from me before.

PHP errors and error reporting are something that many developers new to the language might miss initially. This is because, on many PHP based web server installations, PHP errors may be suppressed by default. This means that no one sees or is even aware of these errors.

For this reason, it’s a good idea to know where and how to enable them, especially for your local development environment. This helps you pick up errors in your code early on.

If you Google «PHP errors» one of the first results you will see is a link to the error_reporting function documentation.

This function allows you to both set the level of PHP error reporting, when your PHP script (or collection of scripts) runs, or retrieve the current level of PHP error reporting, as defined by your PHP configuration.

The error_reporting function accepts a single parameter, an integer, which indicates which level of reporting to allow. Passing nothing as a parameter simply returns the current level set.

There is a long list of possible values you can pass as a parameter, but we’ll dive into those later.

For now it’s important to know that each possible value also exists as a PHP predefined constant. So for example, the constant E_ERROR has the value of 1. This means you could either pass 1, or E_ERROR to the error_reporting function, and get the same result.

As a quick example, if we create a php_error_test.php PHP script file, we can see the current error reporting level set, as well as set it to a new level.

<?php
// echo the current error reporting level
echo error_reporting();
<?php
// report all Fatal run-time errors.
echo error_reporting(1);

Error reporting configuration

Using the error_reporting function in this way is great when you just want to see any errors related to the piece of code you’re currently working on.

But it would be better to control which errors are being reported on in your local development environment, and log them somewhere logical, to be able to review as you code. This can be done inside the PHP initialization (or php.ini) file.

The php.ini file is responsible for configuring all the aspects of PHP’s behavior. In it you can set things like how much memory to allocate to PHP scripts, what size file uploads to allow, and what error_reporting level(s) you want for your environment.

If you’re not sure where your php.ini file is located, one way to find out is to create a PHP script which uses the phpinfo function. This function will output all the information relative to your PHP install.

<?php
phpinfo();

As you can see from my phpinfo, my current php.ini file is located at /etc/php/7.3/apache2/php.ini.

phpinfo

Once you’ve found your php.ini file, open it in your editor of choice, and search for the section called ‘Error handling and logging’. Here’s where the fun begins!

Error reporting directives

The first thing you’ll see in that section is a section of comments which include a detailed description of all the Error Level Constants. This is great, because you’ll be using them later on to set your error reporting levels.

Fortunately these constants are also documented in the online PHP Manual, for ease of reference.

Below this list is a second list of Common Values. This shows you how to set some commonly used sets of error reporting value combinations, including the default values, the suggested value for a development environment, and the suggested values for a production environment.

; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

Finally, at the bottom of all the comments is the current value of your error_reporting level. For local development, I’d suggest setting it to E_ALL, so as to see all errors.

error_reporting = E_ALL

This is usually one of the first things I set when I set up a new development environment. That way I’ll see any and all errors that are reported.

After the error_reporting directive, there are some additional directives you can set. As before, the php.ini file includes descriptions of each directive, but I’ll give a brief description of the important ones below.

The display_errors directive allows you to toggle whether PHP outputs the errors or not. I usually have this set to On, so I can see errors as they happen.

display_errors=On

The display_startup_errors allows for the same On/Off toggling of errors that may occur during PHP’s startup sequence. These are typically errors in your PHP or web server configuration, not specifically your code. It’s recommended to leave this Off, unless you’re debugging a problem and you aren’t sure what’s causing it.

The log_errors directive tells PHP whether or not to log errors to an error log file. This is always On by default, and is recommended.

The rest of the directives can be left as the default, except for maybe the error_log directive, which allows you to specify where to log the errors, if log_errors is on. By default it will log the errors wherever your web server has defined them to be logged.

Custom error logging

I use the Apache web server on Ubuntu, and my project-specific virtual host configurations use the following to determine the location for the error log.

ErrorLog ${APACHE_LOG_DIR}/project-error.log

This means it will log to the default Apache log directory, which is /var/log/apache2, under a file called project-error.log. Usually I replace project with the name of the web project it relates to.

So, depending on your local development environment you may need to tweak this to suit your needs. Alternatively, if you can’t change this at the web server level, you can set it at the php.ini level to a specific location.

error_log = /path/to/php.log

It is worth noting that this will log all PHP errors to this file, and if you’re working on multiple projects that might not be ideal. However, always knowing to check that one file for errors might work better for you, so your mileage may vary.

Find and fix those errors

If you’ve recently started coding in PHP, and you decide to turn error reporting on, be prepared to deal with the fallout from your existing code. You may see some things you didn’t expect, and need to fix.

The advantage though, is now that you know how to turn it all on at the server level, you can make sure you see these errors when they happen, and deal with them before someone else sees them!

Oh, and if you were wondering, the errors I was referring to at the start of this post were related to the fact that I was defining constants incorrectly, by not adding quotes around the constant name.

define(CONSTANT, 'Hello world.');

PHP allowed (and might still allow) this, but it would trigger a notice.

Notice: Use of undefined constant CONSTANT - assumed 'CONSTANT' 

This notice was triggered every time I defined a constant, which for that project was about 8 or 9 times. Not great for someone to see 8 or 9 notices at the top of each page…



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

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

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

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

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

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

error_reporting
int

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

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

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

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

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

display_errors
string

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

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

Замечание:

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

Замечание:

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

display_startup_errors
bool

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

log_errors
bool

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

Замечание:

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

log_errors_max_len
int

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

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

ignore_repeated_errors
bool

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

ignore_repeated_source
bool

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

report_memleaks
bool

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

track_errors
bool

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

html_errors
bool

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

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

xmlrpc_errors
bool

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

xmlrpc_error_number
int

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

docref_root
string

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

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

Замечание:

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

docref_ext
string

Смотрите docref_root.

Замечание:

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

error_prepend_string
string

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

error_append_string
string

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

error_log
string

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

error_log_mode
int

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

syslog.facility
string

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

syslog.filter
string

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

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

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

Замечание:

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


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

syslog.ident
string

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

cjakeman at bcs dot org

13 years ago


Using

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

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

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

display_errors On

then there is a possible solution suggested under error_reporting:

<?php

error_reporting
(E_ALL);

ini_set("display_errors", 1);

include(
"file_with_errors.php");

?>

[Modified by moderator]

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


ohcc at 163 dot com

6 years ago


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

Roger

3 years ago


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

php dot net at sp-in dot dk

8 years ago


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

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


iio7 at protonmail dot com

1 year ago


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

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

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


jaymore at gmail dot com

6 years ago


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

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


A while back I got asked by a friend why -1 works to «turn on everything» with error_reporting(), I thought I’d share the explanation. If you’re already acquainted with binary, you can skip directly to the bottom.

error_reporting uses bitfields in order to determine which aspects of reported errors are turned on, and which are turned off.

Constants such as E_ALL, E_WARN, E_NOTICE etc all contain integer values which correlate directly to individual bits contained within a number. For example, in php5.3 E_ALL equates to the number «30719».

If we convert this number to binary, we can see the individual bits (or switches if you prefer) that make up the number:

php > var_dump(decbin(E_ALL));
string(15) "111011111111111"

You’ll notice that not all the switches are turned on by default. This is because E_STRICT is not included in E_ALL. If we look at E_STRICT, we see this:

php > var_dump(decbin(E_STRICT));
string(12) "100000000000"

If we line up the two numbers from the right, you’ll see that the «1» is actually in the position where the zero would be when padded with zeros to make it the same length (like regular base-10 numbers, leading zeros in binary have no significance but are useful for display purposes):

111011111111111 // E_ALL
000100000000000 // E_STRICT

So, if we wanted to turn E_STRICT on, we would have to turn on that one bit, which we can do with ‘|’ (logical OR). If you think of 1 and 0 as being similar to TRUE and FALSE, the comparison is analogous to what we do with the boolean operator ‘||’, only on each individual bit. since 1 OR 0 is 1, and 1 OR 1 is 1, all bits are turned on. So, «E_ALL | E_STRICT» creates:

php > var_dump(decbin(E_ALL | E_STRICT));
string(15) "111111111111111"

Now, when you use -1, the binary representation looks like this:

php > var_dump(decbin(-1));
string(32) "11111111111111111111111111111111"

Which turns on many more bits than PHP actually uses at present. The benefit to this is that as php expands its error levels, your software will already have those levels turned on.

EDIT:

  • Some people are suggesting that -1 is «a hack» — this simply is not true. -1 in PHP will always equate to «all bits on» because php uses Two’s complement binary. PHP will not suddenly change how it works with numbers.

  • It was also suggested that ~0 is a better approach, which is also acceptable. «~» (bitwise NOT) is bit inversion — it will set all bits that are on to off, and all bits that are off to on. Since 0 has no bits set, it achieves a result identical to -1. Either method works, and what you choose to use will amount to personal preference.

На чтение 11 мин Просмотров 1.2к. Опубликовано 16.10.2021

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

Содержание

  1. Что такое ошибка PHP?
  2. Какие бывают типы ошибок в PHP?
  3. Ошибки синтаксического анализа или синтаксиса
  4. Фатальные ошибки
  5. Предупреждение об ошибках
  6. Уведомление об ошибках
  7. Как включить отчеты об ошибках в PHP
  8. Сколько уровней ошибок доступно в PHP?
  9. Ошибки отображения PHP
  10. Что такое предупреждение PHP?
  11. Как помогают отчеты о сбоях
  12. Завершение отчета об ошибках PHP

Что такое ошибка PHP?

Ошибка PHP — это структура данных, представляющая что-то, что пошло не так в вашем приложении. В PHP есть несколько конкретных способов вызова ошибок. Один из простых способов имитировать ошибку — использовать die()функцию:

die("something bad happened!");

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

<?php

trigger_error("something happened"); //error level is E_USER_NOTICE

//You can control error level
trigger_error("something bad happened", E_USER_ERROR);
?>

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

На самом деле в PHP есть две формы ошибок: стандартные обычные ошибки и исключения.

Исключения были введены в PHP 5. Они дают вам легче семантику, как try, throwи catch. Исключение легко создать. Это следует из большого успеха языков со статической типизацией, таких как C # и Java.

throw new Exception("Yo, something exceptional happened);

Перехват и выдача исключений, как правило, более упрощены, чем более традиционная обработка ошибок PHP. Вы также можете иметь более локализованную обработку ошибок, а не только глобальную обработку ошибок с помощью set_error_handler (). Вы можете окружить конкретную логику блоками try / catch, которые заботятся только о конкретных исключениях:

<?php try {
    doSystemLogic();
} catch (SystemException $e) {
    echo 'Caught system exception ';
}

try {
    doUserLogic();
} catch (Exception $e) {
    echo 'Caught misc exception ';
}
?>

Какие бывают типы ошибок в PHP?

Ошибка PHP — это не одно и то же, но бывает четырех разных типов:

  • синтаксические или синтаксические ошибки
  • фатальные ошибки
  • предупреждения об ошибках
  • замечать ошибки

Ошибки синтаксического анализа или синтаксиса

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

<?php
$age = 25;

if ($age >= 18 {
    echo 'Of Age';
} else {
    echo 'Minor';
}
?>

Запустив приведенный выше сценарий, я получаю следующую ошибку:

Parse error: syntax error, unexpected '{' in <path> on line 4

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

<?php
    $age = 25;

    if ($age >= 18) {
        echo 'Of Age';
    } else {
        echo 'Minor';
    }
?>

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

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

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

Рассмотрим следующий сценарий:

<?php
    function add($a, $b)
    {
        return $a + $b;
    }

    echo '2 + 2 is ' . sum(2, 2);
?>

Как видите, сценарий определяет функцию с именем add, а затем пытается вызвать ее с неправильным именем. Эта ситуация приводит к фатальной ошибке:

Fatal error: Uncaught Error: Call to undefined function sum() in F:xampphtdocstest.php:7 Stack trace: #0 {main} thrown in <path> on line 7

Все, что нужно для решения ошибки, — это изменить вызов функции на правильное имя, добавить:

echo '2 + 2 is ' . add(2, 2);

Предупреждение об ошибках

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

Взгляните на следующий код:

<?php
    $components = parse_url();
    var_dump($components);
?>

После выполнения приведенного выше кода мы получаем следующее предупреждение:

Warning: parse_url() expects at least 1 parameter, 0 given in <path> on line 2

Предупреждение вызывает тот факт, что мы не предоставили параметр функции parse_url. Давайте исправим это:

<?php
    $components = parse_url('https://example.com');
    var_dump($components);
?>

Это устраняет предупреждение:

array(2) { ["scheme"]=> string(5) "https" ["host"]=> string(11) "example.com" }

Уведомление об ошибках

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

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

<?php
    $numbers = "1,2,5,6";
    $parts = explode(",", $integers);

    echo 'The first number is ' . $parts[0];
?>

Как видите, сценарий определяет переменную $ numbers, а затем пытается передать переменную с именем $ inteers в функцию explode.

Неопределенные переменные действительно являются одной из основных причин уведомлений в PHP. Чтобы ошибка исчезла, достаточно изменить переменную $ inteers на $ numbers.

Как включить отчеты об ошибках в PHP

Включить отчеты об ошибках в PHP очень просто. Вы просто вызываете функцию в своем скрипте:

<?php
error_reporting(E_ALL);

//You can also report all errors by using -1
error_reporting(-1);

//If you are feeling old school
ini_set('error_reporting', E_ALL);
?>

Здесь сказано: «Пожалуйста, сообщайте об ошибках всех уровней». Мы рассмотрим, какие уровни есть позже, но считаем это категорией ошибок. По сути, он говорит: «Сообщайте обо всех категориях ошибок». Вы можете отключить отчет об ошибках, установив 0:

<?php
error_reporting(0);
?>

Параметр метода в error_reporting()действительности является битовой маской. Вы можете указать в нем различные комбинации уровней ошибок, используя эту маску, как видите:

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

В нем говорится: «сообщать о фатальных ошибках, предупреждениях и ошибках синтаксического анализатора». Вы можете просто разделить их знаком «|» чтобы добавить больше ошибок. Иногда вам могут потребоваться более расширенные настройки отчетов об ошибках. Вы можете использовать операторы битовой маски для составления отчетов по различным критериям:

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

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

Сколько уровней ошибок доступно в PHP?

В PHP 5 целых 16 уровней ошибок. Эти ошибки представляют категорию, а иногда и серьезность ошибки в PHP. Их много, но многочисленные категории позволяют легко определить, где отлаживать ошибку, исходя только из ее уровня. Итак, если вы хотите сделать что-то конкретное только для ошибок пользователя, например, проверку ввода, вы можете определить обработчик условий для всего, что начинается с E_USER. Если вы хотите убедиться, что вы закрыли ресурс, вы можете сделать это, указав на ошибки, оканчивающиеся на _ERROR.

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

Я хочу остановиться на нескольких популярных из них.

Во-первых, у нас есть общие ошибки:

  • E_ERROR (значение 1): это типичная фатальная ошибка. Если вы видите этого плохого парня, ваше приложение готово. Перезагрузите и попробуйте еще раз.
  • E_WARNING (2): это ошибки, которые не приводят к сбою вашего приложения. Похоже, что большинство ошибок находятся на этом уровне.

Далее у нас есть пользовательские ошибки:

  • E_USER_ERROR (256): созданная пользователем версия указанной выше фатальной ошибки. Это часто создается с помощью trigger_error ().
  • E_USER_NOTICE (1024): созданная пользователем версия информационного события. Обычно это не оказывает неблагоприятного воздействия на приложение, как и log.info ().

Последняя категория, на которую следует обратить внимание, — это ошибки жизненного цикла приложения, обычно с «core» или «compile» в названии:

  • EE_CORE_ERROR (16): Подобно фатальным ошибкам выше, эта ошибка может возникнуть только при запуске приложения PHP.
  • EE_COMPILE_WARNING (128): нефатальная ошибка, которая возникает только тогда, когда скрипт PHP не компилируется.

Есть еще несколько ошибок. Вы можете найти их полный список здесь.

Ошибки отображения PHP

Отображение сообщений об ошибках в PHP часто сбивает с толку. Просто погуглите «Отображение сообщения об ошибке PHP» и посмотрите. Почему так?

В PHP вы можете решить, отображать ли ошибки или нет. Это отличается от сообщения о них. Сообщение о них гарантирует, что ошибки не будут проглочены. Но отображение их покажет их пользователю. Вы можете настроить отображение всех ошибок PHP с помощью директив display_errors и display_startup_errors:

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

Их включение гарантирует, что они будут отображаться в теле веб-ответа пользователю. Обычно рекомендуется отключать их в среде, не связанной с разработкой. Целочисленный параметр метода также является битовой маской, как в error_reporting(). Здесь также применяются те же правила и параметры для этого параметра.

Что такое предупреждение PHP?

Выше вы заметили, что одним из уровней ошибок является E_WARNING. Вы также могли заметить, что многие уровни ошибок имеют версии предупреждений. Я хочу немного в этом разобраться. Основное различие между предупреждением и ошибкой в ​​PHP заключается в том, завершает ли оно приложение. В PHP большинство ошибок фактически не останавливают выполнение скрипта.

Вот пример:

<?php
 $x = 1;
 trigger_error("user warning!", E_USER_WARNING);
 $x = 3;
 echo "$x is  ${$x}";
?>

Вы все равно будете видеть, $x is 3несмотря на срабатывание предупреждения. Это может быть полезно, если вы хотите собрать список ошибок проверки. Я лично предпочитаю использовать исключения в наши дни, но ваш опыт может отличаться.

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

Как помогают отчеты о сбоях

PHP упрощает настройку внешних инструментов отчетов об ошибках, подобных тем, которые предлагает Raygun. Он предоставляет несколько различных ловушек для своей среды выполнения, чтобы обрабатывать ошибки и отправлять их по сети. См. Этот пример, взятый со страницы PHP Raygun :

namespace
{
    // paste your 'requires' statement

    $client = new Raygun4phpRaygunClient("apikey for your application");

    function error_handler($errno, $errstr, $errfile, $errline ) {
        global $client;
        $client->SendError($errno, $errstr, $errfile, $errline);
    }

    function exception_handler($exception)
    {
        global $client;
        $client->SendException($exception);
    }

    set_exception_handler('exception_handler');
    set_error_handler("error_handler");
}

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

    $client = new Raygun4phpRaygunClient("apikey for your application");

Затем мы создаем пару функций, которые обрабатывают наши ошибки и исключения:

 function error_handler($errno, $errstr, $errfile, $errline ) {
        global $client;
        $client->SendError($errno, $errstr, $errfile, $errline);
    }

    function exception_handler($exception)
    {
        global $client;
        $client->SendException($exception);
    }

Обратите внимание, что мы вызываем SendError()функцию, передавая некоторые важные сведения о структуре данных ошибки. Это сделает удаленный вызов Raygun.

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

set_exception_handler('exception_handler');
set_error_handler("error_handler");

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

Имея все это на месте, мы можем получить красиво отформатированный отчет об ошибках

Завершение отчета об ошибках PHP

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

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

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

Понравилась статья? Поделить с друзьями:
  • Error required internal cmake variable not set cmake may not be built correctly
  • Error reported here must be corrected before the service can be started
  • Error reported by freeproxy перевод
  • Error report warface trunk has stopped working
  • Error report unknown command