Htaccess показывать все ошибки php

Содержание:

  • Способы вывода ошибок PHP
  • Виды ошибок в файле .htaccess
  • Как включить вывод ошибок через .htaccess
  • Примеры практического применения
  • Включение журналирования ошибок PHP в .htaccess
  • Дополнительные способы вывода ошибок PHP

Ошибки в коде — неотъемлемая часть любого процесса разработки. Чтобы понять, почему не выполняется скрипт, необходимо вывести error-логи PHP на экран.

Следует помнить, что в публичной версии сайта вывод ошибок на экран должен быть отключён.

  • Через файл .htaccess, отвечающий за дополнительные параметры сервера Apache.
  • Непосредственно через PHP-скрипт.
  • Через файл php.ini, содержащий настройки интерпретатора PHP.

Преимущества вывода ошибок в файле .htaccess

  1. Широкий охват. Параметры распространяются на все элементы дочерних поддиректорий.
  2. Быстрота и удобство. Обработка ошибок настраивается в несколько команд и в одном месте.

Вывод ошибок на экран лучше делать через файл .htaccess, особенно когда PHP-файлов несколько. Поэтому далее разберём этот способ подробнее.

Виды ошибок PHP в файле .htaccess

  • E_ALL — все виды ошибок, кроме E_STRICT до PHP 5.4.0.
  • E_ERROR — фатальные ошибки, прекращающие работу скрипта.
  • E_WARNING — ошибки-предупреждения. Не являются фатальными, поэтому не вызывают прекращение работы скрипта.
  • E_PARSE — ошибки разбора. Могут возникать только во время компиляции.
  • E_NOTICE — уведомления о нарушении времени выполнения скрипта.
  • E_CORE_ERROR — фатальная ошибка обработчика. Генерируется ядром во время запуска PHP-скрипта.
  • E_CORE_WARNING — предупреждения компиляции, возникающие при запуске PHP-скрипта.
  • E_COMPILE_ERROR — фатальные ошибки, возникающие на этапе компиляции.
  • E_COMPILE_WARNING — предупреждение компилятора PHP-скриптов.
  • E_USER_ERROR — ошибки, сгенерированные пользователями.
  • E_USER_WARNING — предупреждения, сгенерированные пользователями.
  • E_USER_NOTICE — уведомления, сгенерированные пользователями.

Как включить вывод ошибок через .htaccess

Файл .htaccess должен находиться в корневой директории сайта (например, «public_html»). Отредактировать его можно с помощью проводника, доступного в панели хостинга.

Примечание. Если файла .htaccess нет, то его необходимо создать.

Включить отображение ошибок PHP и настроить фильтрацию их вывода можно двумя директивами: «display_errors» и «error_reporting». Первая отвечает за состояние режима показа ошибок («On» или «Off»), а вторая задаёт глубину отображения.

Показать ошибки PHP на экране можно с помощью следующего кода:

php_flag display_errors on
php_value error_reporting -1

После сохранения изменённого файла, следует обновить страницу.

Примеры практического применения

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

Следующий код скроет ошибки PHP с экрана:

# скрыть ошибки php
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0

Иногда нужно фиксировать сбои, но нет возможности вывести ошибки PHP на экран  (например, сайт работает в реальном времени). Для этого можно перенаправить вывод информации в лог-файл с помощью следующего кода:

# включить ведение журнала ошибок PHP
php_flag  log_errors on
# месторасположение журнала ошибок PHP
php_value error_log /var/www/имя_пользователя/data/www/ваш_www-домен/

Чтобы обработка ошибок в .htaccess выполнялась безопасно надо обязательно защитить папку с log-файлами от внешнего доступа при помощи следующего кода:

# запретить доступ к журналу ошибок PHP
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>

Можно также настроить фильтрацию. Флаг «integer» указывает на глубину вывода данных (уровень показа). Значение «0» не выведет никаких ошибок. Комбинация «8191» запишет в log-файл сбои всех уровней.

# общая директива для фильтрации ошибок php
php_value error_reporting integer

Чтобы текст ошибок не обрезался, можно установить максимальный размер на строку:

# общая директива для установки максимального размера строки
log_errors_max_len integer

Выключение записи повторяющихся ошибок сократит объём поступающих данных и улучшит восприятие информации:

# отключить запись повторяющихся ошибок
php_flag ignore_repeated_errors on
php_flag ignore_repeated_source on

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

# обработка ошибок PHP для публичного ресурса
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_reporting -1
php_value log_errors_max_len 0

<Files /home/path/public_html/domain/PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>

Во время разработки или отладки файл .htaccess должен содержать следующий код:

# Обработка ошибок PHP во время разработки
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/path/public_html/domain/PHP_errors.log
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1
php_value log_errors_max_len 0

<Files /home/path/public_html/domain/PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>

Включение журналирования ошибок PHP в .htaccess

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

# включение записи PHP ошибок
php_flag log_errors onphp_value error_log /home/path/public_html/domain/PHP_errors.log

Примечание. Вместо «/home/path/public_html/domain/PHP_errors.log» нужно подставить собственный путь до директории, в которой будет вестись журнал ошибок.

Чтобы запретить доступ к журналу извне, нужно добавить следующий код:

# предотвращаем доступ к логу PHP ошибок
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>

Дополнительные способы вывода ошибок PHP

Можно добавить оператор «@», чтобы запретить показ ошибок в конкретной инструкции PHP:

$value = @$var[$key];

Вывод ошибок в PHP-скрипте

Чтобы выводить все ошибки, нужно в начале скрипта прописать:

error_reporting(-1);

Если необходимо отображать ошибки PHP только из определённого места скрипта, то можно использовать следующий код:

ini_set('display_errors', 'On'); // сообщения с ошибками будут показываться
error_reporting(E_ALL); // E_ALL - отображаем ВСЕ ошибки
$value = $var[$key]; // пример ошибки
ini_set('display_errors', 'Off'); // теперь сообщений НЕ будет

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

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

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

error_reporting = E_ALL
display_errors On

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

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

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

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

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

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

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

Через .htaccess

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

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

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on

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

php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

Также выключить .htaccess display errors можно командой:

php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0

Через логи PHP

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

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

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

error_reporting(E_ALL & ~E_NOTICE)

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

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

# disable repeated error logging
php_flag ignore_repeated_errors on
php_flag ignore_repeated_source on

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

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

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

ini_set('display_errors', 'Off')

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

php_flag display_startup_errors on
php_flag display_errors on

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

php_flag display_startup_errors off
php_flag display_errors off

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

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

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

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

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

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

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

sudo apachectl -k graceful

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

error_reporting = E_ALL

display_errors On

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

sudo apachectl -k graceful

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

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

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

Способ 1: Использование файла .htaccess
Для этого откройте файл .htaccess который располагается в корне Вашего сайта (если его нет, то создайте его). И добавьте в него следующие строчки:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on

Если Вам нужно отключить вывод ошибок — замените слово on на off.

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

error_reporting(E_ALL); //вывод всех ошибок
error_reporting(0); //отключение ошибок
error_reporting(E_ALL & ~E_NOTICE); //вывод ошибок, но не предупреждений типа Notice

Все возможные аргументы Вы можете найти в документации на сайта php.net. Иногда так же может быть полезна команда ini_set:

ini_set('display_errors', 1); //включение ошибок

Однако данная команда обычно заблокирована.

Способ 3: Правка файла php.ini
Иногда хостинг провайдер открывает Вам доступ к файлу конфигурации PHP — php.ini. Доступ может быть открыт полностью, либо частично. Если Вы счастливый обладатель такого хостинга, то включить вывод ошибок можно изменив настройку display_errors.

display_errors = on

После чего необходимо перезагрузить apache.

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

Запись опубликована в рубрике PHP с метками .htaccess, display error, hide error, PHP, php.ini, Settings, show error, вывести, ошибки, показать, предупреждения, спрятать. Добавьте в закладки постоянную ссылку.

A PHP application may produce many different levels of errors and warnings when executed. Viewing these errors is critical for developers to troubleshoot an application. However, difficulties are often encountered when trying to display errors from PHP applications, which often fail silently.

Quickest Way to Show All PHP Errors

Adding the following lines to your PHP code is the quickest way to show all PHP errors and warnings:

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

The above functions are directives work as follows:

ini_set()

The ini_set function tries to override the configuration found in the PHP .ini file.

display_errors

The display_errors is a directive that determines whether the errors will be shown to the user or remain hidden. This should usually be disabled after development.

display_startup_errors

The display_startup_errors is also a directive, which is used to find the errors encountered during the PHP startup sequence. This is a separate directive because the display_errors directive does not handle such errors.

Unfortunately, the display_errors and display_startup_errors directives do not show parse errors such as missing semicolons or curly braces. The PHP ini configuration must be modified to achieve this.

error_reporting()

The error_reporting is a native PHP function that is used to show errors. This function can be used to report all types of errors in the PHP script. For that, the named constant E_ALL is used as the argument in the function.

Configure PHP.ini to Display All Errors and Warnings

If adding the above functions and directives does not show all errors, the PHP ini configuration has additional directives that can be modified:

display_errors = on

The display_errors directive can be set to «on» in the PHP.ini file. This will display all errors including syntax and parse errors that are not displayed by only calling the ini_set function in the PHP code.

Note that the display_errors directive must be set to «off» if the application is in production.

The PHP.ini file can be found in the output of the phpinfo() function:

#php 7.x
<?php
phpinfo();
?>

Loaded Configuration File shows the location of the PHP.ini file.

The PHP error_reporting() function

The error reporting function is a built-in function in PHP that allows developers to specify which and how many errors are shown in the application. This function sets the error_reporting directive in the PHP ini configuration during runtime.

error_reporting(0);

The value 0 should be passed to the error_reporting function to remove all errors, warnings, parse messages and notices.

error_reporting(E_NOTICE);

Variables are allowed to be used in PHP even if they are not declared. This is not best practice as undeclared variables cause issues if used in loops and conditions. Undeclared variables are displayed in the web application when E_NOTICE is passed in the error_reporting function.

error_reporting(E_ALL & ~E_NOTICE);

The error_reporting function allows developers to filter which PHP errors can be shown. The “~” character stands for «not» or «no», so the parameter ~E_NOTICE means not to show notices. The «&» character means «true for all».

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

These 3 lines of code do the same thing — they show all PHP errors. The error_reporting(E_ALL) is the most widely used since it is more readable.

Show PHP Errors Through .htaccess Configuration

Directory files are usually accessible to developers. The .htaccess file located in the root or public directory of the project can also be used to enable or disable the directive for showing PHP errors.

php_flag display_startup_errors on
php_flag display_errors on

The .htaccess file has directives for display_startup_errors and display_errors, similar to what will be added to the PHP code to show errors. Development and production can have different .htaccess files by showing or disabling error messages this way, with production suppressing the displaying of errors.

The display_errors directive in .htaccess or the PHP.ini file may need to be configured depending on which files are accessible and how deployments and server configurations are done. Many hosting providers will not allow changes to the PHP.ini file to enable display_errors.

Track, Analyze and Manage PHP Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing and showing PHP errors easier than ever. Try it today

I am testing a website online.

Right now, the errors are not being displayed (but I know they exist).

I have access to only the .htaccess file.

How do I make all errors to display using my .htaccess file?


I added these lines to my .htaccess file:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on

And the pages now display:

Internal server error

Peter Mortensen's user avatar

asked May 25, 2011 at 16:50

Ogugua Belonwu's user avatar

Ogugua BelonwuOgugua Belonwu

2,1016 gold badges28 silver badges45 bronze badges

3

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log

answered May 25, 2011 at 16:54

silex's user avatar

9

php_flag display_errors on

To turn the actual display of errors on.

To set the types of errors you are displaying, you will need to use:

php_value error_reporting <integer>

Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php

Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.

Mukesh Chapagain's user avatar

answered May 25, 2011 at 16:57

UFTimmy's user avatar

UFTimmyUFTimmy

5893 silver badges4 bronze badges

1

I feel like adding more details to the existing answer:

# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /full/path/to/file/php_errors.log
php_value error_reporting -1
php_value log_errors_max_len 0

Give 777 or 755 permission to the log file and then add the code

<Files php_errors.log>
     Order allow,deny
     Deny from all
     Satisfy All
</Files>

at the end of .htaccess.
This will protect your log file.

These options are suited for a development server. For a production server you should not display any error to the end user. So change the display flags to off.

For more information, follow this link: Advanced PHP Error Handling via htaccess

Peter Mortensen's user avatar

answered Jan 8, 2016 at 9:56

Ashish's user avatar

AshishAshish

6597 silver badges19 bronze badges

1

If you want to see only fatal runtime errors:

php_value display_errors on
php_value error_reporting 4

answered Aug 23, 2017 at 23:28

Zeke's user avatar

ZekeZeke

5524 silver badges14 bronze badges

This works for me (reference):

# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off

# Disable display of all other errors
php_flag display_errors off

# Disable HTML markup of errors
php_flag html_errors off

# Enable logging of errors
php_flag log_errors on

# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# Disable ignoring of unique source errors
php_flag ignore_repeated_source off

# Enable logging of PHP memory leaks
php_flag report_memleaks on

# Preserve most recent error via php_errormsg
php_flag track_errors on

# Disable formatting of error reference links
php_value docref_root 0

# Disable formatting of error reference links
php_value docref_ext 0

# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# Disable max error string length
php_value log_errors_max_len 0

# Protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

Peter Mortensen's user avatar

answered Aug 15, 2019 at 14:11

Darkcoder's user avatar

DarkcoderDarkcoder

7921 gold badge7 silver badges17 bronze badges

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.

Introduction

PHP is a server-side scripting language used in web development. As a scripting language, PHP is used to write code (or scripts) to perform tasks. If a script encounters an error, PHP can generate an error to a log file.

In this tutorial, learn how to enable PHP Error Reporting to display all warnings. We also dive into creating an error log file in PHP.

Guide on enabling php errors and reporting

What is a PHP Error?

A PHP error occurs when there is an issue within the PHP code. Even something simple can cause an error, such as using incorrect syntax or forgetting a semicolon, which prompts a notice. Or, the cause may be more complex, such as calling an improper variable, which can lead to a fatal error that crashes your system.

If you do not see errors, you may need to enable error reporting.

To enable error reporting in PHP, edit your PHP code file, and add the following lines:

<?php
error_reporting(E_ALL);
?>

You can also use the ini_set command to enable error reporting:

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

Edit php.ini to Enable PHP Error Reporting

If you have set your PHP code to display errors and they are still not visible, you may need to make a change in your php.ini file.

On Linux distributions, the file is usually located in /etc/php.ini folder.

Open php.ini in a text editor.

Then, edit the display_errors line to On.

This is an example of the correction in a text editor:

php.ini file to enable error reporting to display notifications

Edit .htaccess File to turn on Error Reporting

The .htaccess file, which acts as a master configuration file, is usually found in the root or public directory. The dot at the beginning means it’s hidden. If you’re using a file manager, you’ll need to edit the settings to see the hidden files.

Open the .htaccess file for editing, and add the following:

php_flag display_startup_errors on
php_flag display_errors on

If these values are already listed, make sure they’re set to on.

Save the file and exit.

Other Useful Commands

To display only the fatal warning and parse errors, use the following:

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

You can add any other error types you need. Just separate them with the pipe | symbol.

This list contains all the predefined constants for PHP error types.

One useful feature is the “not” symbol.

To exclude a particular error type from reporting:

<?php
error_reporting(E_ALL & ~E_NOTICE)
?>

In this example, the output displays all errors except for notice errors.

How to Turn Off PHP Error Reporting

To turn off or disable error reporting in PHP, set the value to zero. For example, use the code snippet:

<?php
error_reporting(0);
?>

How to Create an Error Log File in PHP

Error logs are valuable resources when dealing with PHP issues.

To display PHP error logs, edit the .htaccess file by adding the following:

php_value error_log logs/all_errors.log

If you don’t have access to the .htaccess file, you can edit the httpd.conf or apache2.conf file directly.

This log is typically stored in the /var/log/httpd/ or /var/log/apache2/ directory.

To enable error logging, edit your version of the file and add the following:

ErrorLog “/var/log/apache2/website-name-error.log”

You may substitute httpd for apache2 if needed. Likewise, if you’re using nginx, you can use that directory for the error log.

How to Display PHP Errors on a Webpage

Error logs are valuable resources when dealing with PHP issues.

To display PHP error logs, edit the .htaccess file by adding the following:

php_value error_log logs/all_errors.log

If you don’t have access to the file, you can edit the httpd.conf or apache2.conf file directly.

This log is typically stored in the /var/log/httpd/ or /var/log/apache2/ directory.

To enable error logging, edit your version of the file and add the following:

ErrorLog “/var/log/apache2/website-name-error.log”

You may substitute httpd for apache2 if needed. Likewise, if you’re using nginx, you can use that directory for the error log.

Conclusion

This tutorial has provided you with multiple alternatives to enable and show all PHP errors and warnings. By receiving error notifications quickly and accurately, you can improve the ability to troubleshoot PHP issues. If you are implementing new features, installing a new PHP-based app, or trying to locate a bug on your website, it is important to know which PHP version your web server is running before taking any steps.

Опубликовано 27.04.2023 14:00

Оглавление:

Классификация ошибок
Способы вывода ошибок
Какой способ выбрать
Заключение

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

Классификация ошибок

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

  • E_ERROR — фатальные проблемы, из-за которых скрипт прекращает работу. Причиной может быть нехватка памяти, вызов несуществующего класса объектов, битая ссылка на подключаемый файл;
  • E_WARNING — предупреждения об ошибке, которая не относится к фатальным, из-за чего программа продолжает работу. Однако она может выполнять программы не так, как запланировано. Распространенный вид ошибки, который чаще всего вызван неправильным аргументом при вызове функции;
  • E_PARSE — компилятор не понимает, что написано в коде, т. к. разработчик допустил ошибки синтаксиса, например: незакрытые скобки, нет знаков препинания, перепутаны латинские символы и кириллица;
  • E_NOTICE — мелкое нарушение во время выполнения скрипта. Возникает из-за обращения к несуществующим переменным, массивам, неопределенным константам;
  • E_CORE_ERROR — фатальная ошибка обработчика, сгенерированная ядром языка программирования в момент запуска скрипта;
  • E_CORE_WARNING — предупреждения о проблемах с ядром;
  • E_COMPILE_ERROR — сбои, происходящие на этапе компиляции, которые приводят к остановке выполнения программы. Они генерируются скриптовым движком Zend;
  • E_COMPILE_WARNING — уведомления о некритичных сбоях компилятора;
  • E_DEPRECATED — предупреждение о том, что программист использует устаревшие конструкции, которые не будут работать после обновления среды разработки.

Остались вопросы?

Укажите ваши данные, и мы вам перезвоним

Способы вывода ошибок

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

Через .htaccess

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

php_flag display_startup_errors on

php_flag display_errors on

php_flag html_errors on

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

php_flag display_startup_errors off

php_flag display_errors off

php_flag html_errors off

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

Через логи PHP

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

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

error_reporting(E_ALL)

Для отключения вывода ошибок необходимо подставить 0 в скобки — error_reporting(0). Если же нужно убрать логирование только повторов ошибок, рекомендуется воспользоваться командами:

php_flag ignore_repeated_errors on

php_flag ignore_repeated_source on

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

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

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

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

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

ini_set('display_errors', 'On')

error_reporting(E_ALL)

Чтобы отключить вывод программных сбоев, необходимо изменить команду на: ini_set(‘display_errors’, ‘Off’).

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

Найти актуальный INI-файл легко найти, вызвав функцию phpinfo (). Он будет помечен, как файл конфигурации — loaded configuration file.

Остались вопросы?

Укажите ваши данные, и мы вам перезвоним

Какой способ выбрать

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

Команда .htaccess имеет две директивы: display_startup_errors и display_errors. С их помощью можно легко настроить вывод информации о программных сбоях и синтаксических проблемах.

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

Заключение

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

Начинающим разработчикам, которые работают в одном файле и не пользуются веб-серверами, подойдет первый метод отображения. Продвинутым программистам стоит пользоваться логами PHP, которые позволяют управлять выводом, не затрагивая другие скрипты. А администраторам серверов нужно освоить php.ini, т. к. его действие распространяется на все ресурсы, размещенные на одном веб-сервере.

Комплексный курс по PHP

За 6 недель вы освоите работу с главными инструментами современного backend разработчика и получите 3 проекта в портфолио.

  • Создавать проекты на PHP

  • Использовать лучшие инструменты

  • Быстро реализовывать свою идею

  • Защита данных

  • Работать с базами данных

Записаться

Понравилась статья? Поделить с друзьями:
  • Htaccess перенаправление на страницу ошибки
  • Htaccess перенаправление если ошибка 404
  • Htaccess переадресация на 404 ошибку
  • Htaccess ошибка 500 что это
  • Htaccess вывод ошибок в браузер