Error Reporting Itself
ini_set('display_errors', 1);
or display_errors
Simply allows PHP to output errors — useful for debugging, highly recommended to disable for production environments. It often contains information you’d never want users to see.
error_reporting(E_ALL);
or error_reporting
Simply sets exactly which errors are shown.
Setting one or the other will not guarantee that errors will be displayed. You must set both to actually see errors on your screen.
As for setting this up permanently inside your PHP config, the default for error_reporting
is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. That said, this variable should not need changed. See here:
http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
As for displaying errors, see here:
http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors
Set the config value of «display_errors» to either stderr
or stdout
, depending on your need.
Just change these variables inside of your php.ini
file and you’ll be golden. Make absolutely sure both display_errors
and error_reporting
is set to a satisfactory value. Just setting error_reporting
will not guarantee that you see the errors you’re looking for!
Error Reporting Works Everywhere Except When Connecting To My DB!
If you see errors everywhere you need to except in the Database Connection, you just need to do some error catching. If it’s PDO, do something like this:
try {
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $this->DBH->prepare("INSERT INTO `" . $this->table . "` ($fs) value ($ins) $up");
$STH->execute($data);
$id = $this->DBH->lastInsertId();
$this->closeDb();
return $id;
} catch(PDOException $e) {
echo $e->getMessage();
}
Just a snippet from my framework. Of course you’ll have to change it to your liking, but you should be able to get the general idea there. They key is this part here:
try {
//DB Stuff
} catch(PDOException $e) {
echo $e->getMessage();
}
I Still Don’t See The Error
If you’ve done both of what I’ve listed here and still have trouble, your problem has nothing to do with enabling error reporting. The code provided will show you the error with a Database Connection itself, and inside of PHP code. You must have a completely different issue if this has not shown you an error you’re chasing.
You’ll likely need to be a bit more descriptive on exactly what you’re chasing, and what you’re expecting to see.
В этом руководстве мы расскажем о различных способах того, как в 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 включить отображение ошибок. Надеемся, что эта информация была вам полезна.
Блог / Программирование / Настроить Nginx для вывода php ошибок в браузер (а не только в log)
Это не является настройкой nginx, а управляется из конфигурации php-fpm.
Настройте в файле php-fpm.conf (к примеру для 7.4 это /etc/php/7.4/fpm/php-fpm.conf):
php_flag[display_errors] = on php_flag[display_startup_errors] = on |
Написать комментарий
Данная запись опубликована в 07.04.2022 15:30 и размещена в рубрике Программирование.
Вы можете перейти в конец страницы и оставить ваш комментарий.
Мало букафф? Читайте есчо !
Problem Description:
I have been trying for three days now to enable error reporting in PHP. I have gotten by for a while using the ini_set('display errors' 1);
function until I tried to connect to a DB; it didn’t work. Now, I have enabled error_reporting
, display_startup_errors
, log_errors
without any effect on error reporting. I have changed all five config files (the development ini, production ini, the php.ini file(s) located in php/7.0/cli, php/7.0/fpm, and even the one in apache2 (even though I am running nginx)
I am beginning to doubt my own abilities, any assistance is greatly appreciated.
EDIT: I have used the ini_set function described above in my files, and it worked up until I tried to connect to a DB. I have confirmed that I’ve enabled error reporting for the php.ini file described in the phpinfo() function directory path. No effect whatsoever.
Solution – 1
Try:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Solution – 2
Error Reporting Itself
ini_set('display_errors', 1);
or display_errors
Simply allows PHP to output errors – useful for debugging, highly recommended to disable for production environments. It often contains information you’d never want users to see.
error_reporting(E_ALL);
or error_reporting
Simply sets exactly which errors are shown.
Setting one or the other will not guarantee that errors will be displayed. You must set both to actually see errors on your screen.
As for setting this up permanently inside your PHP config, the default for error_reporting
is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. That said, this variable should not need changed. See here:
http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
As for displaying errors, see here:
http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors
Set the config value of «display_errors» to either stderr
or stdout
, depending on your need.
Just change these variables inside of your php.ini
file and you’ll be golden. Make absolutely sure both display_errors
and error_reporting
is set to a satisfactory value. Just setting error_reporting
will not guarantee that you see the errors you’re looking for!
Error Reporting Works Everywhere Except When Connecting To My DB!
If you see errors everywhere you need to except in the Database Connection, you just need to do some error catching. If it’s PDO, do something like this:
try {
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $this->DBH->prepare("INSERT INTO `" . $this->table . "` ($fs) value ($ins) $up");
$STH->execute($data);
$id = $this->DBH->lastInsertId();
$this->closeDb();
return $id;
} catch(PDOException $e) {
echo $e->getMessage();
}
Just a snippet from my framework. Of course you’ll have to change it to your liking, but you should be able to get the general idea there. They key is this part here:
try {
//DB Stuff
} catch(PDOException $e) {
echo $e->getMessage();
}
I Still Don’t See The Error
If you’ve done both of what I’ve listed here and still have trouble, your problem has nothing to do with enabling error reporting. The code provided will show you the error with a Database Connection itself, and inside of PHP code. You must have a completely different issue if this has not shown you an error you’re chasing.
You’ll likely need to be a bit more descriptive on exactly what you’re chasing, and what you’re expecting to see.
Solution – 3
Because no one particularily gave away the answer, I will just have to post it myself.
I found the error.log file (which indeed is logging all errors on my Nginx server) in this directory: /var/log/nginx/error.log
Hopefully this may help others using Nginx as well, but I still do not understand why the **** the errors aren’t showing up in the browser. I think it is Nginx’s nature to make everything quite complicated.
Perhaps I should develop using Apache and then port it into Nginx when I have more experience — just some thoughts for others who are getting into this as well.
I just wanted to give an update on this: Since upgrading from PHP 7.0.2 <= 7.0.3, I am now able to see the errors that should have been displayed.
EDIT: Don’t delete the contents of that log file, it will screw the whole error reporting. I’m back to nothing now. –
Solution – 4
perhaps, it will help you. change values of parameteres
in the file /etc/php/7.0/fpm/pool.d/www.conf (for example value display_errors by default is disabled)
The comment above by the_nuts helped solve it for me. The directory and file didn’t exist.
To diagnose, I added:
print("\n\n<br><br>log_errors: ".ini_get('log_errors'));
print("\n\n<br><br>error_log: ".ini_get('error_log'));
to the top of my code (a WordPress plugin). This outputted:
log_errors: 1
error_log: /usr/local/etc/php-fpm.d/fpm.log
In terminal I used ls to learn the file and directory were missing, i.e.
ls /usr/local/etc/php-fpm.d/fpm.log
ls /usr/local/etc/php-fpm.d/
outputted
ls: cannot access '/usr/local/etc/php-fpm.d/fpm.log': No such file or directory
ls: cannot access '/usr/local/etc/php-fpm.d': No such file or directory
To fix: I changed directory to /usr/local/etc, created the directory, the file and then set the owner to www-data:www-data
cd /usr/local/etc
sudo mkdir php-fpm.d
cd php-fpm.d
sudo touch fpm.log
sudo chown -R www-data:www-data fpm.log
If the file and directory do exist, run
ls fpm.log -l
and if owner is root:
-rw-r--r-- 1 root root 0 Jun 23 19:52 fpm.log
run
sudo chown -R www-data:www-data fpm.log
to give the web server ownership and write access
-rw-r--r-- 1 www-data www-data 12848 Jun 23 20:07 fpm.log