What am I doing wrong here?
I have error_log set in the .ini file along with error_reporting = E_ALL | E_STRICT
.
What else am I missing? This usually gave it to me. I want this set in the .ini file and not in my scripts.
Another interesting thing that is happening is that when I purposefully try and throw an error in one of my scripts, Apache restarts over and over again.
This is my event log after one error. Look at the timestamp.
Wed Nov 04 19:34:23 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:23 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:23 2009] [notice] Parent: Created child process 1700
[Wed Nov 04 19:34:23 2009] [notice] Child 1700: Child process is running
[Wed Nov 04 19:34:23 2009] [notice] Child 3008: Released the start mutex
[Wed Nov 04 19:34:23 2009] [notice] Child 1700: Acquired the start mutex.
[Wed Nov 04 19:34:23 2009] [notice] Child 1700: Starting 64 worker threads.
[Wed Nov 04 19:34:23 2009] [notice] Child 1700: Starting thread to listen on port 80.
[Wed Nov 04 19:34:24 2009] [notice] Child 3008: All worker threads have exited.
[Wed Nov 04 19:34:24 2009] [notice] Child 3008: Child process is exiting
[Wed Nov 04 19:34:53 2009] [notice] Parent: child process exited with status 128 -- Restarting.
[Wed Nov 04 19:34:53 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:53 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:53 2009] [notice] Parent: Created child process 3656
[Wed Nov 04 19:34:53 2009] [notice] Child 3656: Child process is running
[Wed Nov 04 19:34:53 2009] [notice] Child 3656: Acquired the start mutex.
[Wed Nov 04 19:34:53 2009] [notice] Child 3656: Starting 64 worker threads.
[Wed Nov 04 19:34:53 2009] [notice] Child 3656: Starting thread to listen on port 80.
[Wed Nov 04 19:34:53 2009] [notice] Parent: child process exited with status 128 -- Restarting.
[Wed Nov 04 19:34:54 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:54 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:54 2009] [notice] Parent: Created child process 3980
[Wed Nov 04 19:34:54 2009] [notice] Child 3980: Child process is running
[Wed Nov 04 19:34:54 2009] [notice] Child 3980: Acquired the start mutex.
[Wed Nov 04 19:34:54 2009] [notice] Child 3980: Starting 64 worker threads.
[Wed Nov 04 19:34:54 2009] [notice] Child 3980: Starting thread to listen on port 80.
[Wed Nov 04 19:34:54 2009] [notice] Parent: child process exited with status 128 -- Restarting.
[Wed Nov 04 19:34:54 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:54 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:54 2009] [notice] Parent: Created child process 1600
[Wed Nov 04 19:34:54 2009] [notice] Child 1600: Child process is running
[Wed Nov 04 19:34:54 2009] [notice] Child 1600: Acquired the start mutex.
[Wed Nov 04 19:34:54 2009] [notice] Child 1600: Starting 64 worker threads.
[Wed Nov 04 19:34:54 2009] [notice] Child 1600: Starting thread to listen on port 80.
[Wed Nov 04 19:34:55 2009] [notice] Parent: child process exited with status 128 -- Restarting.
[Wed Nov 04 19:34:55 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:55 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:55 2009] [notice] Parent: Created child process 1068
[Wed Nov 04 19:34:55 2009] [notice] Child 1068: Child process is running
[Wed Nov 04 19:34:55 2009] [notice] Child 1068: Acquired the start mutex.
[Wed Nov 04 19:34:55 2009] [notice] Child 1068: Starting 64 worker threads.
[Wed Nov 04 19:34:55 2009] [notice] Child 1068: Starting thread to listen on port 80.
[Wed Nov 04 19:34:55 2009] [notice] Parent: child process exited with status 128 -- Restarting.
[Wed Nov 04 19:34:55 2009] [notice] Apache/2.2.14 (Win32) PHP/5.3.0 configured -- resuming normal operations
[Wed Nov 04 19:34:55 2009] [notice] Server built: Sep 28 2009 22:41:08
[Wed Nov 04 19:34:55 2009] [notice] Parent: Created child process 3220
[Wed Nov 04 19:34:56 2009] [notice] Child 3220: Child process is running
[Wed Nov 04 19:34:56 2009] [notice] Child 3220: Acquired the start mutex.
[Wed Nov 04 19:34:56 2009] [notice] Child 3220: Starting 64 worker threads.
[Wed Nov 04 19:34:56 2009] [notice] Child 3220: Starting thread to listen on port 80.
This has been asked 1000 times and I have browsed through the different posts before posting this, but I have not found an answer. As long as I have been programming with PHP, this have always been a nightmare to get working.
asked Nov 5, 2009 at 2:48
1
Check PHP-FPM is not explicitly setting error_log
:
Make sure the file /etc/php-fpm.d/www.conf
does not contain php_admin_value
settings for error_log. Search for the following and comment them out using a semi-colon:
; NOTE: If these are set, ini_set('error_log', 'path') will have no effect
; inside your php code, and this will be forced to be the value always.
; php_admin_value[error_log] = /var/log/php-fpm/www-error.log
; php_admin_flag[log_errors] = on
Then restart php-fpm:
systemctl restart php-fpm
Check Apache .htaccess files are not setting the error_log
value using
php_admin_value
settings in the Apache configuration files cannot be overridden, so make sure you don’t have any php_admin_value for the error_log
setting in the Apache configuration files. Also check for php_value
settings just in case.
PHP Website — How to change configuration settings
answered Apr 9, 2016 at 8:49
Basil MusaBasil Musa
8,0496 gold badges63 silver badges63 bronze badges
1
Flimm’s Troubleshooting Guide
Here is my troubleshooting guide to error_log()
calls not working.
-
Look at your server’s configuration to find out where the default error log file is.
This depends on which server you’re using. To get you started, have
a look at Apache’sErrorLog
option if you’re using Apache or
Nginx’serror_log
option if you’re using Nginx. Make sure it
is set to a file. If you’re using a tool like Valet, note that it’s
using server software like Nginx behind the scenes. -
Check the permissions of your server’s error log file. On Unix-like systems, it should be writeable by the correct user and group, and the permissions of the parent directory and all its ancestors need to be correct as well. Use
chmod
andchown
. -
Check the configuration of PHP in the
.ini
files. Specifically, check forlog_errors = On
anderror_reporting = E_ALL | E_STRICT
anderror_log = /tmp/example/php_errors.log
(see docs forlog_errors
,error_reporting
anderror_log
configuration settings). To find the.ini
file, look at the output ofphpinfo();
. Iferror_log
is not set, by default it goes to the error log for the server, mentioned in the previous steps. Iferror_log
is set to a file, it should already exist and be writeable, just like in previous steps. Remember to restart the server after configuration changes. -
Check that PHP’s settings aren’t being changed by server configuration. Your server’s configuration (even
.htaccess
) can change PHP configuration settings. In Apache, this is done usingphp_admin_value
andphp_admin_flag
(docs). For instance, you may find in your.htaccess
file this line:php_admin_flag[log_errors] = off
. Remember to restart the server after configuration changes. At this point, you should be able to create a test filetest.php
with the contents<?php error_log("test");
, restart your server, and open the URL in your browser, and you should be able to seetest
in your error log (either the server’s, or the one specified byerror_log =
). But keep reading. -
Check that PHP’s settings aren’t being changed at run-time. The
log_errors
option can be changed at runtime by runningini_set('log_errors', 1);
, and so can the other configuration optionserror_reporting
anderror_log
. Also note there is a specialerror_reporting()
PHP function which changes the configuration at run-time. Search your code-base for any invocations ofini_set
orerror_reporting
. WordPress for example does run these depending on the value ofWP_DEBUG
.
Other things to look at: You may be having permission issues in SELinux (see this answer).
JamesHoux
2,9103 gold badges31 silver badges48 bronze badges
answered Nov 8, 2018 at 11:16
FlimmFlimm
133k45 gold badges249 silver badges260 bronze badges
4
You also need to set log_errors = On
in file php.ini.
answered Nov 5, 2009 at 2:54
chaoschaos
122k33 gold badges303 silver badges309 bronze badges
5
In case anyone else is having trouble getting their local development environment to log errors, here’s what fixed it for me:
On Windows, error_log
must be set to the complete path to the log for error_log()
to work (error_log = c:apachephp_errors.log
). However, if error_log = php_errors.log
with no path, php will still be able to log startup errors such as
PHP Startup: Unable to load dynamic library ‘extphp_mysqli.dll’ — The specified module could not be found
answered Nov 13, 2012 at 22:20
Mel ReamsMel Reams
2053 silver badges5 bronze badges
1
The problem I ran into was that the error log I had designated was write-protected. All my .htaccess settings were correct, but PHP just couldn’t write to the error log, because it didn’t have any permissions. This fixed it right up for me:
chmod 777 watermellon-app-errors.log
Obviously, you’re going to want to change the .log part to whatever file you’re using for a log.
answered Oct 8, 2012 at 18:58
4
If the error_log directive is set, the file will be used for recording PHP errors. When it is not set, errors will be logged to the Apache log. Take a look at error_log.
The error_log file and the directory it’s in must be writable by the user that Apache is running under. If the file isn’t being created, it’s probably due to a permissions issue.
I don’t know for sure why Apache would be crashing on you, but I’m guessing it’s a permissions issue of some sort.
answered Nov 18, 2009 at 8:04
bradymbradym
4,8801 gold badge31 silver badges36 bronze badges
0
I don’t understand why, but the error log is now working. Here is what I did.
I gave up and commented back out the error_log directive and closed the ini file. I ran the script with the parse error to see if Apache would still crash and I got the PHP error in the log file. This is freaky, because the ini file no longer has error_log enabled and my script is not using ini_set().
Bhargav Rao
49.5k28 gold badges121 silver badges140 bronze badges
answered Nov 5, 2009 at 4:24
JimJim
4111 gold badge4 silver badges6 bronze badges
1
In my case, on a CentOS development server, after a full yum update
, the permission on /var/log/http was changed to 700 and the user to ‘root’, so the user ‘apache’ wasn’t able to enter or write into it.
It was still able to write into the existing file /var/log/httpd/error.log, but it wasn’t able to create a new file, as I use date-suffixed log files.
Issuing the command
chown apache /var/log/httpd
solved the problem.
answered Sep 21, 2017 at 16:40
Zoltan MZoltan M
1211 silver badge3 bronze badges
1
If you are using Fedora, SELinux (enabled by default) will prevent Apache / httpd from appending errors to your log file even when your file is specified in file php.ini and its containing directory has all permissions allowed.
You can see if this is happening by looking at your system log file in /var/log/messages
The ideal solution is to configure SELinux to allow access to the log file.
The quicker solution is to disable SELinux in /etc/selinux/config by setting SELINUX to disabled.
You’ll need to reboot your system after doing this for the change to take effect.
answered Mar 23, 2015 at 14:49
AnthonyAnthony
7221 gold badge8 silver badges25 bronze badges
3
For me, manually creating the file, /var/log/php_error.log, solved the issue:
-
In file php.ini, configure log to file
log_errors = On error_log = /var/log/php_error.log
-
Restart Apache
sudo systemctl restart apache2
-
Create the log file, for example:
sudo touch /var/log/php_error.log
-
Give the correct rights (owner must be Apache)
sudo chown www-data:root /var/log/php_error.log
(And if not already set)
sudo chmod 0644 /var/log/php_error.log
-
Test this way, for example:
sudo vim /var/www/.../index.php
<html> <body> PHP file: <?php echo "Hello, World!"; trigger_error("User error in PHP", E_USER_ERROR); ?> </body> </html>
-
Check the error is written
sudo less /var/log/php_error.log
answered Sep 16, 2021 at 12:30
user219901user219901
711 silver badge6 bronze badges
1
For further debugging:
phpinfo();
It shows the current error_log setting, next to the error_log value in phpinfo() and can be useful when a vhost isn’t logging.
I ended up here after that setting got overridden from file php.ini and the vhost. I ended up logging to syslog.
answered Sep 3, 2019 at 13:35
themulletthemullet
8338 silver badges14 bronze badges
2
As bradym said, check whether you have write permissions to the directory where you PHP error log is located for the Apache user. If you created a log file with written permissions it’s not enough; the directory should have them too.
answered Dec 10, 2010 at 14:44
I had the same issue and fixed it by doing this:
chmod 0777 -R /var/log/apache2
apachectl restart
I think PHP runs as user www-data
while access to /var/log/apache2
is limited to root
. So, this fixes it.
answered Aug 18, 2020 at 7:14
supersansupersan
5,5932 gold badges43 silver badges63 bronze badges
The error_log = "C:phpLogerror.log"
line was not working for me either. The solution for me was that you shouldn’t create the error.log yourself, because PHP will do it for you. See the PHP message board. I’m using PHP 5.2 on a Windows Server 2008 server.
answered Jul 28, 2011 at 8:50
CerveserCerveser
7128 silver badges23 bronze badges
This did the trick for me.
setsebool -P httpd_unified 1
Please note, this would be the preferred method below to try first:
semanage fcontext -a -t httpd_sys_rw_content_t 'errorLogNameHere.error.log
restorecon -v 'errorLogNameHere.error.log'
This answer was derived from the logs from executing this command line:
journalctl -xe
Further information on the system I was running on:
PHP 7.0 and CentOS 7
I am not sure if it’s not obvious, but the issue was Apache’s configuration to writing files. I did try chmod 777, chmod a+w on the logging directory, but this didn’t work for me.
answered Nov 12, 2017 at 8:59
1
Ну ок, будем считать, что дело теперь не в апаче.
Кроме log_errors надо включать также и error_reporting, например так:
Файл, куда эти ошибки записываются, должен быть доступен для записи под юзером, из под которого у тебя работает пхп. Делать 777 у /var/log не советую, лучше завести под это отдельный каталог.
Также убедись, что php.ini читается процессом пхп. Создай файл с phpinfo(), попробуй изменить в php.ini какой-то параметр, и смотри на результат. Возможно, придется перезапустить вебсервер.
Значения error_reporting и log_errors могут перезаписываться твоей CMS, поэтому желательно изменять эти директивы через ее конфиг. Кроме этого, эти параметры могут меняться и напрямую в скриптах, т.е. без использования настроек CMS, так что если все вышеперечисленное не сработает, то погрепай свой сайт на их наличие.
Deleted
(23.05.18 10:14:50 MSK)
- Показать ответ
- Ссылка
-
#1
PHP не ведет лог
Добрый день.
Дано: Debian с apache и php. Симптомы: php ничего не пишет в лог апача.
php-файлы апачем обрабатываются, проверил.
В php.ini написано
Код:
error_reporting = E_ALL & ~E_DEPRECATED
log_errors = On
Опция error_log не задана.
Используется именно этот файл, проверил с помощью php —ini.
Апач все «своё» исправно пишет в /var/log/apache2/error.log.
Что это может быть?
-
#2
посмотри настройки логов через phpinfo()
-
#3
Автор оригинала: dimagolov
посмотри настройки логов через phpinfo()
Loaded Configuration File /etc/php5/apache2/php.ini
error_log no value no value
error_reporting 22527 22527
log_errors On On
-
#4
error_log no value no value
вот потому и не ведет… определи куда он будет писаться и все будет.
-
#5
Автор оригинала: dimagolov
вот потому и не ведет… определи куда он будет писаться и все будет.
Мануал как бы намекает, что ошибки по умолчанию шлются в лог Апача, нет?
http://ru.php.net/manual/en/errorfunc.configuration.php#ini.error-log:
If this directive is not set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or stderr in CLI.
Upd: Кроме того, проверил у себя на ноутбуке (Убунту), ровно то же самое показывает phpinfo, но в лог ошибки пишутся.
-
#6
кстати да, должно идти в лог апача. может скрипт переопределяет, тот который не пишет в лог? ты проверял конкретно генерацию ошибок после phpinfo()? и кстати, а как пхп-то исполняется?
-
#7
Автор оригинала: dimagolov
кстати да, должно идти в лог апача. может скрипт переопределяет, тот который не пишет в лог? ты проверял конкретно генерацию ошибок после phpinfo()? и кстати, а как пхп-то исполняется?
Нет, не скрипт. Я написал тестовый скрипт, такой:
PHP:
<?php
print "test 1";
aaa();
print "test 2";
?>
Работает, как и ожидается. В error.log об ошибке ни слова. Если скормить этот же файл php в консоли, всё тоже ожидаемо:
Код:
php -e test.php
test 1PHP Fatal error: Call to undefined function aaa() in /var/www/test.php on line 3
-
#8
кстати да, должно идти в лог апача.
Если как модуль. А вот про FCGI я сталкивался с тем, что эррор_лог не велся, но навскидку не вспомню, нужно доку читать.
-
#9
А вот про FCGI я сталкивался с тем, что эррор_лог не велся, но навскидку не вспомню, нужно доку читать
флопп,
а ты прикинь мозгами-то, если пхп как запущен как фсги, как он узнает куда писать (имя файла), и каким образом он это будет делать? Это два не связанных ничем, кроме как временного сокетного соединения, процесса.
-
#10
а ты прикинь мозгами-то, если пхп как запущен как фсги, как он узнает куда писать
Ты не поверишь — пхп как модуль тоже не знает, где лежит апачевский лог. Он ошибки выдает в STDERR. Разница в том, что FCGI шный STDERR ловить некому.
-~{}~ 08.09.10 22:42:
Более того, почитав мануал:
FastCGI uses a single connection for all the data associated with an application — stdin, stdout, stderr, and environment variables. The data on the connection is encapsulated using a FastCGI protocol that allows stdin and the environment variables to share the same half connection (on the way in) and stdout and stderr to share the half connection (on the way out).
Так что должен ловить. А та проблема, которая вертелась у меня в голове — я вспомнил, php-fpm-овский STDERR почему-то не ловился лайти. Скорее всего, это был этот баг — http://redmine.lighttpd.net/issues/499
-
#11
/etc/php-fpm.conf
; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Default Value: no
;catch_workers_output = yes
-
#12
fixxxer, спасибо. ) Наверное, и правда оно.
Настройка во время выполнения
Поведение этих функций зависит от установок в php.ini.
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
error_reporting | NULL | PHP_INI_ALL | |
display_errors | «1» | PHP_INI_ALL | |
display_startup_errors | «1» | PHP_INI_ALL |
До PHP 8.0.0 значение по умолчанию было "0" .
|
log_errors | «0» | PHP_INI_ALL | |
log_errors_max_len | «1024» | PHP_INI_ALL | Не имеет смысла в версии PHP 8.0.0, удалено в версии PHP 8.1.0. |
ignore_repeated_errors | «0» | PHP_INI_ALL | |
ignore_repeated_source | «0» | PHP_INI_ALL | |
report_memleaks | «1» | PHP_INI_ALL | |
track_errors | «0» | PHP_INI_ALL | Объявлено устаревшим в PHP 7.2.0, удалено в PHP 8.0.0. |
html_errors | «1» | PHP_INI_ALL | |
xmlrpc_errors | «0» | PHP_INI_SYSTEM | |
xmlrpc_error_number | «0» | PHP_INI_ALL | |
docref_root | «» | PHP_INI_ALL | |
docref_ext | «» | PHP_INI_ALL | |
error_prepend_string | NULL | PHP_INI_ALL | |
error_append_string | NULL | PHP_INI_ALL | |
error_log | NULL | PHP_INI_ALL | |
error_log_mode | 0o644 | PHP_INI_ALL | Доступно, начиная с PHP 8.2.0 |
syslog.facility | «LOG_USER» | PHP_INI_SYSTEM | Доступно, начиная с PHP 7.3.0. |
syslog.filter | «no-ctrl» | PHP_INI_ALL | Доступно, начиная с PHP 7.3.0. |
syslog.ident | «php» | PHP_INI_SYSTEM | Доступно, начиная с PHP 7.3.0. |
Для подробного описания констант
PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.
Краткое разъяснение конфигурационных
директив.
-
error_reporting
int -
Задаёт уровень протоколирования ошибки. Параметр может быть либо числом,
представляющим битовое поле, либо именованной константой.
Соответствующие уровни и константы приведены в разделе
Предопределённые константы,
а также в php.ini. Для установки настройки во время выполнения используйте функцию
error_reporting(). Смотрите также описание директивы
display_errors.Значение по умолчанию равно
E_ALL
.До PHP 8.0.0 значение по умолчанию было:
.E_ALL
&
~E_NOTICE
&
~E_STRICT
&
~E_DEPRECATED
При этой настройке не отображаются уровни ошибокE_NOTICE
,
E_STRICT
иE_DEPRECATED
.Замечание:
PHP-константы за пределами PHPИспользование PHP-констант за пределами PHP, например в файле
httpd.conf, не имеет смысла, так как в таких случаях требуются
целочисленные значения (int). Более того, с течением времени будут
добавляться новые уровни ошибок, а максимальное значение константы
E_ALL
соответственно будет расти. Поэтому в месте, где
предполагается указатьE_ALL
, лучше задать большое целое число,
чтобы перекрыть все возможные битовые поля. Таким числом может быть, например,
2147483647
(оно включит все возможные ошибки, не
толькоE_ALL
). -
display_errors
string -
Эта настройка определяет, требуется ли выводить ошибки на экран вместе
с остальным выводом, либо ошибки должны быть скрыты от пользователя.Значение
"stderr"
посылает ошибки в потокstderr
вместоstdout
.Замечание:
Эта функциональность предназначена только для разработки и не должен использоваться в
готовых производственных системах (например, системах, имеющих доступ в интернет).Замечание:
Несмотря на то, что display_errors может быть установлена во время выполнения
(функцией ini_set()), это ни на что не повлияет, если в скрипте есть
фатальные ошибки. Это обусловлено тем, что ожидаемые действия программы во время
выполнения не получат управления (не будут выполняться). -
display_startup_errors
bool -
Даже если display_errors включена, ошибки, возникающие во время запуска PHP, не будут
отображаться. Настойчиво рекомендуем включать директиву display_startup_errors только
для отладки. -
log_errors
bool -
Отвечает за выбор журнала, в котором будут сохраняться сообщения об ошибках. Это
может быть журнал сервера или error_log.
Применимость этой настройки зависит от конкретного сервера.Замечание:
Настоятельно рекомендуем при работе на готовых работающих
web сайтах протоколировать ошибки там, где они отображаются. -
log_errors_max_len
int -
Задание максимальной длины log_errors в байтах. В
error_log добавляется информация
об источнике. Значение по умолчанию 1024. Установка значения в 0
позволяет снять ограничение на длину log_errors. Это ограничение
распространяется на записываемые в журнал ошибки, на отображаемые ошибки,
а также на $php_errormsg, но не на явно вызываемые функции,
такие как error_log().Если используется int, значение измеряется байтами. Вы также можете использовать сокращённую запись, которая описана в этом разделе FAQ.
-
ignore_repeated_errors
bool -
Не заносить в журнал повторяющиеся ошибки. Ошибка считается
повторяющейся, если происходит в том же файле и в той же строке, и если настройка
ignore_repeated_source выключена. -
ignore_repeated_source
bool -
Игнорировать источник ошибок при пропуске повторяющихся сообщений. Когда
эта настройка включена, повторяющиеся сообщения об ошибках не будут
заноситься в журнал вне зависимости от того, в каких файлах и строках они происходят. -
report_memleaks
bool -
Если настройка включена (по умолчанию), будет формироваться отчёт об утечках памяти,
зафиксированных менеджером памяти Zend. На POSIX платформах этот отчёт будет
направляться в поток stderr. На Windows платформах он будет посылаться в отладчик
функцией OutputDebugString(), просмотреть отчёт в этом случае можно с помощью утилит,
вроде » DbgView. Эта настройка имеет
смысл в сборках, предназначенных для отладки. При этом
E_WARNING
должна быть включена в список error_reporting. -
track_errors
bool -
Если включена, последняя произошедшая ошибка будет первой в переменной
$php_errormsg. -
html_errors
bool -
Если разрешена, сообщения об ошибках будут включать теги HTML. Формат для
HTML-ошибок производит нажимаемые ссылки, ведущие на описание ошибки, либо
функии, в которой она произошла. За такие ссылки ответственны
docref_root и
docref_ext.Если запрещена, то ошибки будут выдаваться простым текстом, без форматирования.
-
xmlrpc_errors
bool -
Если включена, то нормальное оповещение об ошибках отключается и, вместо него,
ошибки выводятся в формате XML-RPC. -
xmlrpc_error_number
int -
Используется в качестве значения XML-RPC элемента faultCode.
-
docref_root
string -
Новый формат ошибок содержит ссылку на страницу с описанием ошибки или
функции, вызвавшей эту ошибку. Можно разместить копию
описаний ошибок и функций локально и задать ini директиве значение
URL этой копии. Если, например, локальная копия описаний доступна по
адресу"/manual/"
, достаточно прописать
docref_root=/manual/
. Дополнительно, необходимо
задать значение директиве docref_ext, отвечающей за соответствие
расширений файлов файлам описаний вашей локальной копии,
docref_ext=.html
. Также возможно использование
внешних ссылок. Например,
docref_root=http://manual/en/
или
docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon
&url=http%3A%2F%2Fwww.php.net%2F"В большинстве случаев вам потребуется, чтобы значение docref_root оканчивалось
слешем"/"
. Тем не менее, бывают случаи, когда
это не требуется (смотрите выше, второй пример).Замечание:
Эта функциональность предназначена только для разработки, так как он облегчает
поиск описаний функций и ошибок. Не используйте его в готовых
производственных системах (например, имеющих доступ в интернет). -
docref_ext
string -
Смотрите docref_root.
Замечание:
Значение docref_ext должно начинаться с точки
"."
. -
error_prepend_string
string -
Строка, которая будет выводиться непосредственно перед сообщением об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке. -
error_append_string
string -
Строка, которая будет выводиться после сообщения об ошибке.
Используется только тогда, когда на экране отображается сообщение об ошибке.
Основная цель — добавить дополнительную HTML-разметку к сообщению об ошибке. -
error_log
string -
Имя файла, в который будут добавляться сообщения об ошибках. Файл
должен быть открыт для записи пользователем веб-сервера. Если
используется специальное значениеsyslog
, то
сообщения будут посылаться в системный журнал. На Unix-системах это
syslog(3), на Windows NT — журнал событий. Смотрите также: syslog().
Если директива не задана, ошибки будут направляться в SAPI журналы.
Например, это могут быть журналы ошибок Apache или поток
stderr
командной строки CLI.
Смотрите также функцию error_log(). -
error_log_mode
int -
Режим файла, описанного в error_log.
-
syslog.facility
string -
Указывает, какой тип программы регистрирует сообщение.
Действует только в том случае, если опция error_log установлена в «syslog». -
syslog.filter
string -
Указывает тип фильтра для фильтрации регистрируемых сообщений.
Разрешённые символы передаются без изменений; все остальные записываются в шестнадцатеричном представлении с префиксомx
.-
all
– строка будет разделена
на символы новой строки и все символы будут переданы без изменений
-
ascii
– строка будет разделена
на символы новой строки, а любые непечатаемые 7-битные символы ASCII будут экранированы
-
no-ctrl
– строка будет разделена
на символы новой строки, а любые непечатаемые символы будут экранированы
-
raw
– все символы передаются в системный
журнал без изменений, без разделения на новые строки (идентично PHP до 7.3)
Параметр влияет на ведение журнала через error_log установленного в «syslog» и вызовы syslog().
Замечание:
Тип фильтра
raw
доступен начиная с PHP 7.3.8 и PHP 7.4.0.
Директива не поддерживается в Windows.
-
-
syslog.ident
string -
Определяет строку идентификатора, которая добавляется к каждому сообщению.
Действует только в том случае, если опция error_log установлена в «syslog».
cjakeman at bcs dot org ¶
14 years ago
Using
<?php ini_set('display_errors', 1); ?>
at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.
This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set
display_errors On
then there is a possible solution suggested under error_reporting:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
[Modified by moderator]
You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).
ohcc at 163 dot com ¶
6 years ago
If you set the error_log directive to a relative path, it is a path relative to the document root rather than php's containing folder.
iio7 at protonmail dot com ¶
1 year ago
It's important to note that when display_errors is "on", PHP will send a HTTP 200 OK status code even when there is an error. This is not a mistake or a wrong behavior, but is because you're asking PHP to output normal HTML, i.e. the error message, to the browser.
When display_errors is set to "off", PHP will send a HTTP 500 Internal Server Error, and let the web server handle it from there. If the web server is setup to intercept FastCGI errors (in case of NGINX), it will display the 500 error page it has setup. If the web server cannot intercept FastCGI errors, or it isn't setup to do it, an empty screen will be displayed in the browser (the famous white screen of death).
If you need a custom error page but cannot intercept PHP errors on the web server you're using, you can use PHPs custom error and exception handling mechanism. If you combine that with output buffering you can prevent any output to reach the client before the error/exception occurs. Just remember that parse errors are compile time errors that cannot be handled by a custom handler, use "php -l foo.php" from the terminal to check for parse errors before putting your files on production.
Roger ¶
3 years ago
When `error_log` is set to a file path, log messages will automatically be prefixed with timestamp [DD-MMM-YYYY HH:MM:SS UTC]. This appears to be hard-coded, with no formatting options.
php dot net at sp-in dot dk ¶
8 years ago
There does not appear to be a way to set a tag / ident / program for log entries in the ini file when using error_log=syslog. When I test locally, "apache2" is used.
However, calling openlog() with an ident parameter early in your script (or using an auto_prepend_file) will make PHP use that value for all subsequent log entries. closelog() will restore the original tag.
This can be done for setting facility as well, although the original value does not seem to be restored by closelog().
jaymore at gmail dot com ¶
6 years ago
Document says
So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).
But it is better to set "-1" as the E_ALL value.
For example, in httpd.conf or .htaccess, use
php_value error_reporting -1
to report all kind of error without be worried by the PHP version.
Когда на сервере не работает один из сайтов — причины следует искать в программном коде, прежде всего следует изучить лог ошибок РНР (актуально для большинства сайтов, РНР является самым популярным языком веб-программирования). В рамках материала рассмотрено как включить лог ошибок php.
Включение лога ошибок PHP в php.ini
Все параметры РНР — в том числе, версия — задаются в файле php.ini, в нем же включается ведение лога программных ошибок. Если для сервера используется какая-либо панель управления — логирование можно включить в ней, если настройки сделаны вручную, то и ведение лога нужно включать вручную.
Делается это следующим образом:
display_errors = Off
log_errors = On
error_log = /var/log/php-errors.log
При активации display_errors ошибки будут выводится на экран, в директиве error_log задается путь к файлу, в который будет писаться информация необходимая для отладки проекта.
Затем нужно создать файл php-errors.log, на него необходимо выставить права позволяющие веб-серверу записывать в файл данные. В Debian подобных системах Apache работает от имени системного пользователя www-data
touch /var/log/php-errors.log
chown www-data: /var/log/php-errors.log
Затем нужно перезапустить веб-сервер, для Debian/Ubuntu
systemctl reload apache2
Для Centos
systemctl reload httpd
Получилось или нет можно увидеть в phpinfo. Там же можно посмотреть режим работы РНР (если это Apache Handler, то есть еще один способ включения лога, об этом ниже).
Как узнать еще режим работы PHP и текущее значение параметра error_log
Можно создать в корне сайта, работающего с сервера файл phpinfo и поместить в него одну функцию
<?php
phpinfo();
?>
И обратиться к файлу из браузера
http://sitename.com/phpinfo.php
Если применяются редиректы может потребоваться временно переименовать файл .htaccess в корне сайта.
В выводе phpinfo.php можно будет увидеть всю информацию о существующих настройках РНР
Режим работы РНР в примере Apache 2.0 Handler — РНР работает в режиме модуля веб-сервера.
Значение error_log отсутствует, значит в данной конфигурации логирование на уровне конфигурации сервера не включено.
Описанный выше порядок действий позволит включить логирование ошибок РНР при любом режиме работы РНР. При отладке работы сайта при конфигурации с mod-apache следует также проверять логи веб-сервера.
Вся информация будет в них, логи нужно искать в /var/log/apache2 и /var/log/httpd в зависимости от дистрибутива. Лог можно найти выполнив
grep -rl sitename.com /etc/apache
grep -i log файл_из_вывода_предыдущей_команды | grep log
Как включить лог ошибок php в .htacccess при использовании Apache с mod_php
При использовании Apache с mod_php есть альтернативный вариант не требующий редактирования php.ini.
В .htaccess в корне сайта добавляется:
php_flag log_errors On
php_value error_log /var/log/php-errors.log
Выключается логирование установкой основной опции в Off
php_flag log_errors Off
Плюс такого способа в том, что его можно использовать на серверах где нет root доступа. Настройки будут применяться не ко всему серверу, а только к сайту в корне которого добавлен .htaccess.
С fast_cgi директива php_flag работать не будет — возникнет ошибка 500.
Читайте про ошибку 500 и ее причины. Очень часто она появляется как следствие неверной отработки скриптов или настроек сервера не удовлетворяющим требованиям программного кода сайта.