Php error reporting for one page

Как вывести ошибки PHP на экран

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

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

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

Включение вывода ошибок PHP на экран с помощью файла .htaccess

Это очень удобный способ для отладки PHP кода. Работает практически во всех случаях. В папку со скриптом на сайте помещаем файл .htaccess со следующим содержимым:

php_flag display_errors on php_flag display_startup_errors on php_flag error_reporting E_ALL
  • display_errors — включает опцию для вывода ошибок на экран вместе с остальным кодом.
  • display_startup_errors — включает опцию вывода ошибок, возникающих при запуске PHP, когда еще не работает директива display_errors.
  • error_reporting — указывает, какие ошибки выводятся по уровню значимости. При значении директивы E_ALL отображаются все ошибки.
Читайте также:  Test if string is empty python

Включение вывода ошибок PHP на экран в коде файла PHP

Этот способ удобен тем, что выводом ошибок на экран вы управляете в самом скрипте PHP. Параметры, заданные с помощью функции ini_set(), имеют более высокий приоритет и перекрывают директивы php.ini и .htaccess. Разместите следующий код в начале PHP файла:

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

Включение вывода ошибок PHP на экран с помощью файла php.ini

Этот способ актуален когда вы являетесь администратором сервера. В файле php.ini отредактируйте следующие строки (добавьте при необходимости):

display_errors = On display_startup_errors = On error_reporting = E_ALL

Лучший способ вывода PHP ошибок на экран

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

Благодарности

Источник

Php error reporting for single page?

Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Report all errors error_reporting(E_ALL); // To display errors use, Solution 2: If you call within a PHP script, it will only affect that script’s runtime (i.e. anything it executes after that call, including other scripts which have been included).

PHP error_reporting() Function

Example

Specify different error level reporting:

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

// Same as error_reporting(E_ALL);
ini_set(«error_reporting», E_ALL);

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

Definition and Usage

The error_reporting() function specifies which errors are reported.

PHP has many levels of errors, and using this function sets that level for the current script.

Syntax

Parameter Values

Parameter Description
level Optional. Specifies the error-report level for the current script. Error numbers and named constants are accepted. Note: named constant s are recommended to ensure compatibility for future PHP versions

Technical Details

Return Value: Returns the old error reporting level or the current error reporting level if no level parameter is given
PHP Version: 4.0+
PHP Changelog: PHP 5.4: E_STRICT is now a part of E_ALL.
PHP 5.3: New: E_DEPRECATED and E_USER_DEPRECATED.
PHP 5.2: New: E_RECOVERABLE_ERROR.
PHP 5.0: New: E_STRICT .

PHP Error Reference

PHP error_reporting() Function, W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more. Code sampleerror_reporting(0);error_reporting(E_ERROR | E_WARNING | E_PARSE);error_reporting(E_ALL);ini_set(«error_reporting», E_ALL);error_reporting(E_ALL & ~E_NOTICE);Feedback

Php error reporting for single page?

Is it possible (and if so, how) to turn on php error reporting to the screen for just one page? I currently have all error reporting to the screen switched off in php ini.

Or another way of asking — if I use error_reporting(E_ALL) on a single page, will it also display errors on other pages (what I don’t want)?

Using error_reporting(E_ALL) will enable error reporting for only that page!

To display errors use, ini_set(«display_errors», 1)

If you call error_reporting() within a PHP script, it will only affect that script’s runtime (i.e. anything it executes after that call, including other scripts which have been included). It won’t modify server configuration etc.

However, it’s worth noting that if the script encounters an error before it can make that call, it won’t have any effect (i.e. error reporting behaviour will be unchanged). That can be a particular problem if you have a syntax error or similar.

EDIT: It occurs to me that you may want to leave error reporting enabled in your configuration, but only enable display_errors as needed. That way you can still get errors written to a log file, but they’ll only appear on-screen when you want.

Call error_reporting(0) at the beginning of a script to do this. It will block all runtime errors. However, it isn’t recommended to do this, except possibly in production code.

Read more about error_reporting() here

Php error reporting for single page?, Thanks guys. I know you’re all right, because I remember using error_reporting(E_ALL) in the past, but the errors still aren’t showing (but they are logging to error_log files, which they have always done). Will error_reporting() override (for that page) any settings I may have set in config files on the server? –

What are differences between error_reporting(E_ALL) and error_reporting(E_ALL & ~E_NOTICE)

Could anyone explain differences between error_reporting(E_ALL); and error_reporting(E_ALL & ~E_NOTICE); ?

I noticed that when I change from E_ALL to E_ALL & ~E_NOTICE , an error which I was hacking, disappears.

E_ALL & ~E_NOTICE is «everything except notices»

Notices are the least-urgent kinds of messages. But they can be very useful for catching **** programmer mistakes, like trying to read from a hash with a non-existent key, etc.

(To understand the syntax, read up on bitwise operators )

E_ALL would should all the error and warning and notice — everything

E_NOTICE is a special error level, showing things that won’t produce error but are not good or gonna be obsolete in future release of PHP. The notice error level is meant to encourage best practices.

Also it should be error_reporting(E_ALL ^ E_NOTICE); to report everything except notice.

You are advice during development to set the error reporting to E_ALL and fix all the notice errors .

a look in the manual would give much more details.

E_ALL is a flag E_NOTICE is a flag as well

so when you do bitwise operation of ~ which is NOT you’ll exclude E_NOTICE from E_ALL

Under the hood following happens

E_ALL = 111111111111111 E_NOTICE = 000000000001000 

then php can internally check if notices are ON with &(AND) operator

111111111110111 000000000001000 

1 & 0 = 0 it means it is turned off. If however you didn’t use ~ NOT then it would be 1 & 1 = 1 it means that flag is SET

There are other options for example OR to turn on the flag, or XOR to change the flag to opposite state. Basically, this is how flags work.

Php — What are differences between, E_ALL is a flag E_NOTICE is a flag as well. so when you do bitwise operation of ~ which is NOT you’ll exclude E_NOTICE from E_ALL. Under the hood following happens. in decimal. E_ALL = 32767 E_NOTICE = 8 they are power of 2 . bitwise. E_ALL = 111111111111111 E_NOTICE = 000000000001000 result of …

Источник

Оцените статью