Apache вывод ошибок в браузер

При отладке скриптов на 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 отображаются все ошибки.

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

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

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

  1. http://drupalace.ru/lesson/vyvod-oshibok-php-na-ekran
  2. https://help.sweb.ru/entry/137
  3. http://ramzes.ws/blog/vkljuchit-vyvod-oshibok-php
  4. http://php.net/manual/ru/function.error-reporting.php

DEV environment

This always works for me:

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

However, this doesn’t make PHP to show parse errors occurred in the same file — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

PROD environment

Note that above recommentdtion is only suitable for the dev environment. On a live site it must be

display_errors = off
log_errors = on

And then you’ll be able to see all errors in the error log. See Where to find PHP error log

AJAX calls

In case of AJAX call, on a dev server open DevTools (F12), then Network tab.
Then initiate the request which result you want to see, and it will appear in the Network tab. Click on it and then the Response tab. There you will see the exact output.
While on a live server just check the error log all the same.

Your Common Sense's user avatar

answered Jan 29, 2014 at 11:25

Fancy John's user avatar

Fancy JohnFancy John

38k3 gold badges26 silver badges27 bronze badges

16

You can’t catch parse errors in the same file where error output is enabled at runtime, because it parses the file before actually executing anything (and since it encounters an error during this, it won’t execute anything). You’ll need to change the actual server configuration so that display_errors is on and the approriate error_reporting level is used. If you don’t have access to php.ini, you may be able to use .htaccess or similar, depending on the server.

This question may provide additional info.

Your Common Sense's user avatar

answered Jun 27, 2009 at 19:14

Michael Madsen's user avatar

Michael MadsenMichael Madsen

54.1k8 gold badges72 silver badges83 bronze badges

0

Inside your php.ini:

display_errors = on

Then restart your web server.

j0k's user avatar

j0k

22.5k28 gold badges79 silver badges89 bronze badges

answered Jan 8, 2013 at 9:27

user1803477's user avatar

user1803477user1803477

1,6151 gold badge10 silver badges4 bronze badges

5

To display all errors you need to:

1. Have these lines in the PHP script you’re calling from the browser (typically index.php):

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

2.(a) Make sure that this script has no syntax errors

—or—

2.(b) Set display_errors = On in your php.ini

Otherwise, it can’t even run those 2 lines!

You can check for syntax errors in your script by running (at the command line):

php -l index.php

If you include the script from another PHP script then it will display syntax errors in the included script. For example:

index.php

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

// Any syntax errors here will result in a blank screen in the browser

include 'my_script.php';

my_script.php

adjfkj // This syntax error will be displayed in the browser

answered Jan 29, 2014 at 9:52

andre's user avatar

andreandre

1,8311 gold badge16 silver badges8 bronze badges

2

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

Peter Mortensen's user avatar

answered May 18, 2013 at 15:01

Kalhua's user avatar

KalhuaKalhua

5594 silver badges2 bronze badges

1

Warning: the below answer is factually incorrect. Nothing has been changed in error handling, uncaught exceptions are displayed just like other errors. Suggested approach must be used with caution, because it outputs errors unconditionally, despite the display_error setting and may pose a threat by revealing the sensitive information to an outsider on a live site.

You might find all of the settings for «error reporting» or «display errors» do not appear to work in PHP 7. That is because error handling has changed. Try this instead:

try{
     // Your code
} 
catch(Error $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Or, to catch exceptions and errors in one go (this is not backward compatible with PHP 5):

try{
     // Your code
} 
catch(Throwable $e) {
    $trace = $e->getTrace();
    echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

Your Common Sense's user avatar

answered Mar 28, 2016 at 19:26

Frank Forte's user avatar

Frank ForteFrank Forte

1,97119 silver badges18 bronze badges

9

This will work:

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

Peter Mortensen's user avatar

answered May 5, 2014 at 13:23

Mahendra Jella's user avatar

Mahendra JellaMahendra Jella

5,4001 gold badge33 silver badges38 bronze badges

1

Use:

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

This is the best way to write it, but a syntax error gives blank output, so use the console to check for syntax errors. The best way to debug PHP code is to use the console; run the following:

php -l phpfilename.php

Peter Mortensen's user avatar

answered May 4, 2016 at 19:14

Abhijit Jagtap's user avatar

Abhijit JagtapAbhijit Jagtap

2,7102 gold badges29 silver badges43 bronze badges

0

Set this in your index.php file:

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

Peter Mortensen's user avatar

answered Sep 26, 2017 at 12:32

Sumit Gupta's user avatar

Sumit GuptaSumit Gupta

5674 silver badges12 bronze badges

0

Create a file called php.ini in the folder where your PHP file resides.

Inside php.ini add the following code (I am giving an simple error showing code):

display_errors = on

display_startup_errors = on

Peter Mortensen's user avatar

answered Mar 31, 2015 at 18:38

NavyaKumar's user avatar

NavyaKumarNavyaKumar

5875 silver badges3 bronze badges

In order to display a parse error, instead of setting display_errors in php.ini you can use a trick: use include.

Here are three pieces of code:

File: tst1.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Missing " and ;
echo "Testing

When running this file directly, it will show nothing, given display_errors is set to 0 in php.ini.

Now, try this:

File: tst2.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include ("tst3.php");

File: tst3.php

<?php
// Missing " and ;
echo "Testing

Now run tst2.php which sets the error reporting, and then include tst3. You will see:

Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4

Your Common Sense's user avatar

answered May 20, 2017 at 12:07

Peter's user avatar

PeterPeter

1,23719 silver badges32 bronze badges

4

If, despite following all of the above answers (or you can’t edit your php.ini file), you still can’t get an error message, try making a new PHP file that enables error reporting and then include the problem file. eg:

error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('problem_file.php');

Despite having everything set properly in my php.ini file, this was the only way I could catch a namespace error. My exact scenario was:

//file1.php
namespace ab;
class x {
    ...
}

//file2.php
namespace cd;
use cdx; //Dies because it's not sure which 'x' class to use
class x {
    ...
}

answered Apr 24, 2015 at 2:55

jxmallett's user avatar

jxmallettjxmallett

4,0671 gold badge28 silver badges35 bronze badges

2

I would usually go with the following code in my plain PHP projects.

if(!defined('ENVIRONMENT')){
    define('ENVIRONMENT', 'DEVELOPMENT');
}

$base_url = null;

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'DEVELOPMENT':
            $base_url = 'http://localhost/product/';
            ini_set('display_errors', 1);
            ini_set('display_startup_errors', 1);
            error_reporting(E_ALL);
            break;

        case 'PRODUCTION':
            $base_url = 'Production URL'; /* https://google.com */
            error_reporting(E_ALL);
            ini_set('display_errors', 0);
            ini_set('display_startup_errors', 0);
            ini_set('log_errors', 1); // Mechanism to log errors
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

Your Common Sense's user avatar

answered Feb 1, 2017 at 7:16

Channaveer Hakari's user avatar

If you somehow find yourself in a situation where you can’t modifiy the setting via php.ini or .htaccess you’re out of luck for displaying errors when your PHP scripts contain parse errors. You’d then have to resolve to linting the files on the command line like this:

find . -name '*.php' -type f -print0 | xargs -0 -n1 -P8 php -l | grep -v "No syntax errors"

If your host is so locked down that it does not allow changing the value via php.ini or .htaccess, it may also disallow changing the value via ini_set. You can check that with the following PHP script:

<?php
if( !ini_set( 'display_errors', 1 ) ) {
  echo "display_errors cannot be set.";
} else {
  echo "changing display_errors via script is possible.";
}

answered Jan 11, 2016 at 12:11

chiborg's user avatar

chiborgchiborg

26.7k14 gold badges96 silver badges115 bronze badges

1

You can do something like below:

Set the below parameters in your main index file:

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

Then based on your requirement you can choose which you want to show:

For all errors, warnings and notices:

    error_reporting(E_ALL); OR error_reporting(-1);

For all errors:

    error_reporting(E_ERROR);

For all warnings:

    error_reporting(E_WARNING);

For all notices:

    error_reporting(E_NOTICE);

For more information, check here.

Peter Mortensen's user avatar

answered Feb 1, 2017 at 7:33

Binit Ghetiya's user avatar

Binit GhetiyaBinit Ghetiya

1,9092 gold badges21 silver badges31 bronze badges

1

You can add your own custom error handler, which can provide extra debug information. Furthermore, you can set it up to send you the information via email.

function ERR_HANDLER($errno, $errstr, $errfile, $errline){
    $msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
    <b>File:</b> $errfile <br>
    <b>Line:</b> $errline <br>
    <pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

    echo $msg;

    return false;
}

function EXC_HANDLER($exception){
    ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
    $error = error_get_last();
    if ($error["type"] == 1) {
        ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
    }
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");

Peter Mortensen's user avatar

answered Jun 4, 2017 at 14:41

lintabá's user avatar

lintabálintabá

7319 silver badges18 bronze badges

Accepted asnwer including extra options. In PHP files for in my DEVELOPMENT apache vhost (.htaccess if you can ensure it doesn’t get into production):

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

However, this doesn’t make PHP to show parse errors — the only way to show those errors is to modify your php.ini with this line:

display_errors = on

(if you don’t have access to php.ini, then putting this line in .htaccess might work too):

// I've added some extra options that set E_ALL as per https://www.php.net/manual/en/errorfunc.configuration.php.
php_flag log_errors on
php_flag display_errors on
php_flag display_startup_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/mywebsite.ext/logs/php.error.log

answered Jan 8, 2022 at 22:17

webcoder.co.uk's user avatar

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

Peter Mortensen's user avatar

answered May 9, 2017 at 3:28

Joel Wembo's user avatar

Joel WemboJoel Wembo

8146 silver badges10 bronze badges

The best/easy/fast solution that you can use if it’s a quick debugging, is to surround your code with catching exceptions. That’s what I’m doing when I want to check something fast in production.

try {
    // Page code
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

Peter Mortensen's user avatar

answered Mar 27, 2017 at 2:31

Xakiru's user avatar

XakiruXakiru

2,5161 gold badge15 silver badges11 bronze badges

3

    <?php
    // Turn off error reporting
    error_reporting(0);

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

    // Report all errors
    error_reporting(E_ALL);

    // Same as error_reporting(E_ALL);
    ini_set("error_reporting", E_ALL);

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

While your site is live, the php.ini file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.

Lahiru Mirihagoda's user avatar

answered May 24, 2018 at 8:48

pardeep's user avatar

pardeeppardeep

3591 gold badge5 silver badges7 bronze badges

0

Just write:

error_reporting(-1);

answered Jan 13, 2017 at 18:56

jewelhuq's user avatar

jewelhuqjewelhuq

1,20014 silver badges19 bronze badges

0

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this
setting is set to 1 then errors will always be displayed, no matter
what the setting of PHP’s display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3
This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

Peter Mortensen's user avatar

answered Oct 19, 2017 at 5:45

Peter Haberkorn's user avatar

If it is on the command line, you can run php with -ddisplay_errors=1 to override the setting in php.ini:

php -ddisplay_errors=1 script.php

Peter Mortensen's user avatar

answered Oct 24, 2019 at 23:11

gvlasov's user avatar

gvlasovgvlasov

18.4k20 gold badges73 silver badges109 bronze badges

Report all errors except E_NOTICE

error_reporting(E_ALL & ~E_NOTICE);

Display all PHP errors

error_reporting(E_ALL);  or ini_set('error_reporting', E_ALL);

Turn off all error reporting

error_reporting(0);

answered Dec 31, 2019 at 10:07

Shaikh Nadeem's user avatar

In Unix CLI, it’s very practical to redirect only errors to a file:

./script 2> errors.log

From your script, either use var_dump() or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:

fwrite(STDERR, "Debug infosn"); // Write in errors.log^

Then from another shell, for live changes:

tail -f errors.log

or simply

watch cat errors.log

answered Nov 26, 2019 at 2:28

NVRM's user avatar

NVRMNVRM

11.1k1 gold badge86 silver badges85 bronze badges

2

If you are on a SharedHosting plan (like on hostgator)… simply adding

php_flag display_errors 1

into a .htaccess file and uploading it to the remote folder may not yield the actual warnings/errors that were generated on the server.

What you will also need to do is edit the php.ini

This is how you do it via cPanel (tested on hostgator shared hosting
plan)

After logging into your cPanel, search for MultiPHP INI Editor.
It is usually found under the SOFTWARE section in your cPanel list of items.

On the MultiPHP INI Editor page …you can stay on the basic mode tab and just check the button on the line that says display_errors.
Then click the Apply button to save.

enter image description here

IMPORTANT: Just remember to turn it back off when you are done debugging; because this is not recommended for public servers.

answered Mar 13, 2022 at 17:21

Really Nice Code's user avatar

Really Nice CodeReally Nice Code

1,1041 gold badge13 silver badges22 bronze badges

As it is not clear what OS you are on these are my 2 Windows cents.
If you are using XAMPP you need to manually create the logs folder under C:xamppphp. Not your fault, ApacheFriends ommitted this.

To read and follow this file do.

Get-Content c:xamppphplogsphp_error_log -Wait

To do this in VSCode create a task in .vscodetasks.json

{ 
  // See https://go.microsoft.com/fwlink/?LinkId=733558 
  // for the documentation about the tasks.json format 
  "version": "2.0.0", 
  "tasks": [ 
    { 
      "label": "Monitor php errors", 
      "type": "shell", 
      "command": "Get-Content -Wait c:\xampp\php\logs\php_error_log", 
      "runOptions": { 
        "runOn": "folderOpen" 
      } 
    } 
  ] 

and have it run on folder load.

answered Dec 3, 2022 at 14:40

theking2's user avatar

theking2theking2

2,0071 gold badge25 silver badges32 bronze badges

Содержание:

  • Способы вывода ошибок 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.

  • FanatPHP

Всем привет. Почему apache не отображает ошибки в браузере? В файле /etc/php/7.2/apache2/php.ini установил значения: 5b61c72f9fdab743587846.png

В файле index.php где находится мой проект прописал:

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

И ошибок все равно нету!! Не отображается, просто белый экран.
В логах апача ошибки показываются, а в браузере нет. Как исправить??


  • Вопрос задан

    более трёх лет назад

  • 361 просмотр

Потому что apache2 к ошибкам пхп не имеет вообще никакого отношения.
А все установленные в php.ini значения могут быть переписаны в коде.

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

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

Пригласить эксперта


  • Показать ещё
    Загружается…

08 июн. 2023, в 22:08

50000 руб./за проект

08 июн. 2023, в 22:01

3000 руб./за проект

08 июн. 2023, в 21:41

10000 руб./за проект

Минуточку внимания

PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:

  • E_ALL – все ошибки,
  • E_ERROR – критические ошибки,
  • E_WARNING – предупреждения,
  • E_PARSE – ошибки синтаксиса,
  • E_NOTICE – замечания,
  • E_CORE_ERROR – ошибки обработчика,
  • E_CORE_WARNING – предупреждения обработчика,
  • E_COMPILE_ERROR – ошибки компилятора,
  • E_COMPILE_WARNING – предупреждения компилятора,
  • E_USER_ERROR – ошибки пользователей,
  • E_USER_WARNING – предупреждения пользователей,
  • E_USER_NOTICE – уведомления пользователей.

1

Вывод ошибок в браузере

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

PHP

В htaccess

php_value error_reporting "E_ALL"
php_flag display_errors On

htaccess

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

2

Запись ошибок в лог файл

error_reporting(E_ALL);
ini_set('display_errors', 'Off'); 
ini_set('log_errors', 'On');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');

PHP

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

Order Allow,Deny
Deny from all

htaccess

Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):

<FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
Order Allow,Deny
Deny from all
</FilesMatch>

htaccess

3

Отправка ошибок на e-mail

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

Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.

register_shutdown_function('error_alert');

function error_alert() 
{ 
	$error = error_get_last();
	if (!empty($error)) {
		mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); 
	}
}

PHP

Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.

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

function error_alert($type, $message, $file, $line, $vars)
{
	$error = array(
		'type'    => $type,
		'message' => $message,
		'file'    => $file,
		'line'    => $line
	);
	error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
}

set_error_handler('error_alert');

PHP

4

Пользовательские ошибки

PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():

trigger_error('Пользовательская ошибка', E_USER_ERROR);

PHP

Результат:

Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
  • E_USER_ERROR – критическая ошибка,
  • E_USER_WARNING – не критическая,
  • E_USER_NOTICE – сообщения которые не являются ошибками,
  • E_USER_DEPRECATED – сообщения о устаревшем коде.

10.10.2019, обновлено 09.10.2021

Другие публикации

HTTP коды

Список основных кодов состояния HTTP, без WebDAV.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

Работа с JSON в PHP

JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

Пример парсинга html-страницы на phpQuery

phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Подключение к платежной системе Сбербанка

После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

Понравилась статья? Поделить с друзьями:
  • Ap initialization before microcode loading ошибка 02
  • Aovo s3 new ошибка e7
  • Aorus b450 elite коды ошибок
  • Android приложение сервисы google play произошла ошибка
  • Android приложение youtube произошла ошибка