Php allow all errors

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

По умолчанию в PHP 8 отключён показ ошибок, поэтому если во время выполнения PHP скрипта возникла проблема, то на экран ничего не будет выведено. Если ошибка в программе произошла до вывода HTML кода, то вы увидите белый экран веб-браузера.

Где настраивается вывод ошибок в PHP

Вывод ошибок настраивается в:

  • коде скрипта
  • .htaccess файле
  • в конфигурационном файле PHP (например, в php.ini)

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

Настройки в файле .htaccess влияют на все скрипты, находящиеся в данной директории и поддиректориях.

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

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

Настройка вывода ошибок в PHP скрипте

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

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

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

Читайте также:  Tailwind css установка npm

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

Настройка вывода ошибок в журналы веб-сервера выполняется отдельно.

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

Настройка вывода ошибок PHP в файле .htaccess

Включение вывода ошибок в файле .htaccess выполняется следующими директивами:

php_flag display_startup_errors on php_flag display_errors on

Чтобы они сработали, необходимо, чтобы на веб-сервере была включена поддержка файлов .htaccess.

Вывод ошибок в журнал веб-сервера выполняется следующей директивой:

php_value error_log logs/all_errors.log

Настройка вывода всех ошибок в файле php.ini

Файл php.ini — это конфигурационный файл PHP.

При своей работе PHP может использовать более одного конфигурационного файла.

Расположение файла php.ini:

  • В Debian и производных дистрибутивах (Ubuntu, Linux Mint, Kali Linux и прочих) зависит от версии PHP, например, для PHP 8.1 путь до файла следующий: /etc/php/8.1/apache2/php.ini
  • В Arch Linux и производных дистрибутивах (Manjaro, BlackArch и прочих): /etc/php/php.ini

В файле php.ini вы найдёте следующие директивы:

display_errors = Off display_startup_errors = Off

Для включения вывода ошибок замените их на:

display_errors = On display_startup_errors = On

По умолчанию значение error_reporting установлено на:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

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

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

  • E_ALL (Показать все ошибки, предупреждения и уведомления, включая стандарты написания кода.)
  • E_ALL & ~E_NOTICE (Показать все ошибки, кроме уведомлений)
  • E_ALL & ~E_NOTICE & ~E_STRICT (Показать все ошибки, кроме уведомлений и предупреждений о стандартах написания кода.)
  • E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Показать только ошибки)

Для того, чтобы изменения, сделанные в файле php.ini, вступили в силу, необходима перезагрузка веб-сервера.

  • В Debian и производных дистрибутивах (Ubuntu, Linux Mint, Kali Linux и прочих) это делается командой:
sudo systemctl restart apache2.service
sudo systemctl restart httpd.service

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

Если вы создали файл в корневой папке веб-сервера, то в веб-браузере откройте адрес http://localhost/info.php.

На следующем скриншоте показано, что вывод ошибок отключён в файле php.ini:

На этом скриншоте видно, что вывод ошибок включён в файле php.ini:

Вывод ошибок в журнал веб-сервера

Настройка вывода ошибок в журнал веб-сервера настраивается в файле php.ini.

Для этого используется следующая директива:

Расположение файла с ошибка настраивается в конфигурации веб-сервера.

Директива «error_reporting(‘all’);» и ошибка «Uncaught TypeError: error_reporting()»

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

Вы столкнётесь с ошибкой Uncaught TypeError: error_reporting().

[Wed Jul 06 07:29:19.410966 2022] [php:error] [pid 14101] [client 127.0.0.1:58402] PHP Fatal error: Uncaught TypeError: error_reporting(): Argument #1 ($error_level) must be of type ?int, string given in /srv/http/suip/index.php:3\nStack trace:\n#0 /srv/http/suip/index.php(3): error_reporting('all')\n#1 \n thrown in /srv/http/suip/index.php on line 3, referer: http://localhost/suip/

Вместо ‘all‘ вам нужно указать константу, выражающую уровень сообщения об ошибках. Допустимые значения провидены на этой страницы: https://www.php.net/manual/errorfunc.constants.php

Следующая запись является правильной для PHP 8 и означает показывать все ошибки, замечания и рекомендации:

Источник

PHP Error Reporting: How to Enable & Display All Errors / Warnings

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.

How to Display all PHP Errors

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:

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

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.

Other Useful Commands

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

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:

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:

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.

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.

Источник

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