Где посмотреть ошибки php

I can guarantee you, I am not the only person who has been driven to madness at least once in a frustrating search for a log file. It seems like it should be the easiest thing to find in the whole system.

A definitive guide on where the PHP error log is stored would be a complicated bit of work. The official PHP manual does not even try to address the whole topic, because there are dependencies on systems outside PHP, such as the operating system (Linux vs. Windows, which distribution of Linux), including settings within Windows and Linux that affect the name and location of the PHP error log.

Until someone takes the time to write a complete, cross-system guide, the best you are going to get is general directions where you can inquire. Every PHP developer has had to endure agony in this pursuit, with one exception. If you work in one place and the information is provided when you first need it, then you have the information need forever, that is, until you find yourself in a new working environment. There are such fortunate people.

If the information is not given to you on a silver platter, so to speak, you have some hunting to do. The hunt is not the longest you will face in your career, but it is not the simplest either.

As is evident from the many answers already posted, a smart place to begin is the output of phpinfo(). To view it, create a PHP file containing this:

<?php
    phpinfo();

Either browse to that file or run it from the command line. If you do both, you likely will find the error_log is in different places, depending on command line vs. web server use of PHP. That is because the PHP interpreter that runs on a web server is not the same PHP interpreter that runs from the command line, even when the command line is on the same machine as the web server. The answers already posted in here mostly are making an unstated assumption that PHP is running as part of a web server.

Sample output from phpinfo() via web server and web browser

The default for error_log is no value

Default error_log in php running as an Apache mod.

Whatever the value is, it comes from the php.ini files used to configure PHP. There can be many php.ini files. Finding your way among them is confusing at first, but you do not need to deal with this to find your PHP log.

If the output from phpinfo() shows a full path to a file, that is where the log is. You are lucky.

The trick is there usually is not a full path indicated in phpinfo(). When there is not a full path, the location depends on:

  1. Whether error_log is no value. If it is, the log file location will depend on the operating system and the mode PHP is running. If PHP is running as an Apache module, on Linux the log often is in /var/log/apache2/error.log. Another likely spot is in a logs directory in your account home directory, ~/logs/error.log.

  2. If there is a file name without a path, the location depends on whether the file name has the value syslog. If it syslog, then the PHP error log is injected into the syslog for the server, which varies by Linux distribution. A common location is /var/log/syslog, but it can be anywhere. Even the name of the syslog varies by distribution.

  3. If the name without a path is not syslog, a frequent home for the file is is the document root of the website (a.k.a., website home directory, not to be confused with the home directory for your account).

This cheat sheet has been helpful in some situations, but I regret to have to admit it is not nearly universal. You have my condolences.

Enter image description here

Как посмотреть логи PHP

Логи PHP — это важный инструмент для отслеживания ошибок и предупреждений, возникающих во время работы вашего веб-приложения. В этой статье мы рассмотрим, как найти и просмотреть логи PHP на вашем сервере.

1. Определение местоположения логов PHP

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

  • Для Linux: /var/log/php_errors.log или /var/log/httpd/error_log
  • Для Windows (WAMP, XAMPP): C:\wamp\logs\php_error.log или C:\xampp\php\logs\php_error_log

Вы также можете проверить значение директивы error_log в файле конфигурации php.ini для определения местоположения файла логов на вашем сервере:

error_log = /path/to/your/php_error.log

2. Просмотр логов PHP

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

  • С помощью текстового редактора (Notepad, Vim, Nano и т.д.)
  • С помощью командной строки (например, команда tail в Linux)
  • С помощью FTP-клиента (если логи находятся на удаленном сервере)
  • С помощью специализированных инструментов для просмотра логов

3. Разбор ошибок и предупреждений в логах

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

  • Parse error — синтаксическая ошибка в коде, которую необходимо исправить;
  • Fatal error — критическая ошибка, которая приводит к остановке выполнения скрипта;
  • Warning — предупреждение о потенциальной проблеме, которое не останавливает выполнение скрипта, но может вызвать нежелательное поведение;
  • Notice — уведомление о возможной проблеме, которая не влияет на работу скрипта, но может указывать на проблемы в коде или настройках сервера.

4. Исправление ошибок и предупреждений

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

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

5. Мониторинг логов PHP

Регулярное просматривание логов PHP поможет вам оперативно обнаруживать и исправлять ошибки и предупреждения, возникающие в вашем веб-приложении. Вы также можете использовать специализированные инструменты и сервисы для мониторинга логов, которые автоматизируют процесс сбора, анализа и оповещения о возникающих проблемах.

Теперь вы знаете, как найти и просмотреть логи PHP на вашем сервере, а также как разбираться с ошибками и предупреждениями. Это поможет вам поддерживать стабильную и безопасную работу вашего веб-приложения.

как посмотреть логи пхп

Если у вас сайт на PHP, даже самый простой, время от времени в его скриптах могут возникать ошибки. Это может привести к различным неприятным последствиям, от некорректной работы некоторых компонентов сайта (например, формы обратной связи), до недоступности сайта целиком. Как самостоятельно распознать тип ошибки PHP и понять, что с ней делать дальше?

Этот материал поможет вам, во-первых, самостоятельно оценить ситуацию (и, возможно, даже решить ее), а во-вторых, точно ускорит диагностику и решение проблемы при обращении в службу поддержки. Самые ценные советы по устранению наиболее частых ошибок PHP, связанных с лимитами оперативной памяти, вы найдете в конце статьи.

error 500

Как обнаружить ошибку PHP на сайте

1. Встроенными средствами браузера

Итак, если на сайте вместо привычной страницы ничего не отображается (вы видите “пустую страницу”), то, вероятнее всего, в одном из скриптов возникла ошибка. В этом можно убедиться, воспользовавшись встроенными «Инструментами разработчика» вашего браузера. В каждом браузере они могут называться немного по-разному, но суть от этого не меняется.

Например, в браузере Google Chrome это вкладка Dev Tools (или «Инструменты разработчика»). В Mozilla Firefox — это расширение Firebug  (его нужно установить отдельно в меню Adds On) или же вкладка Developer.

Внутри «Инструментов разработчика» нас интересует вкладка, которая называется Network (или Net, или каким-то похожим образом).

Если на странице сайта присутствует ошибка, в этой вкладке вы увидите код ответа 500 (“Internal Server Error”).Ошибка 505 server error

2. Если вывод сообщений об ошибках в браузер отключен

Случается, что вывод сообщений об ошибках в браузер отключён. Чтобы сообщение об ошибке отображалось в браузере, достаточно добавить в файл .htaccess в корневой директории сайта следующую строку:

php_value display_errors on

Файл .htaccess вы найдете по адресу: /home/login/domains/domain.ru/public_html/, где вместо login следует подставить логин вашего аккаунта, а вместо domain.ru — домен вашего сайта.

После сохранения файла .htaccess и обновления страницы вы сможете увидеть ошибку.

Если сайтом используется, например, CMS WordPress, то отображение ошибок можно также включить, заменив в файле wp-config.php:

 define(‘WP_DEBUG’, false);

на:

define(‘WP_DEBUG’, true);

3. С помощью журнала ошибок PHP

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

 php_value error_log /home/login/domains/domain.ru/log/errors.log

Здесь /home/login/domains/domain.ru/log/errors.log — это полный путь до файла, в который будут записываться ошибки PHP (если файла с таким именем нет, он будет создан автоматически при появлении ошибки).
Теперь, если мы снова зайдем на сайт с ошибкой (либо обновим страницу с ошибкой), то в errors.log будут записаны сообщения об ошибках.

Журнал ошибок PHP можно просмотреть, например, с помощью файлового менеджера в Панели управления, открыв файл errors.log:

03

Также можно открыть файл с ошибками и нажать кнопку “Включить автообновление”. Таким образом, новые записи в журнале можно просматривать в реальном времени.

 Расшифровка ошибок PHP

Как правило, в сообщении об ошибке достаточно подробно указано где именно и при выполнении какой части кода она возникла. Например:

Сообщение об ошибке PHP Здесь ошибка заключается в следующем:

Fatal error: Call to undefined function weblizar_get_options() in /home/login/domains/domain.ru/public_html/wp-content/themes/enigma/header.php on line 14

“Вызов неопределенной функции weblizar_get_options() в файле используемой на сайте темы enigma”.

Вероятнее всего, был поврежден один из файлов темы, поэтому можно восстановить только директорию темы ./wp-content/themes/enigma/ , а не всего сайта.

Что делать, в зависимости от типа ошибки PHP

Условно ошибки PHP можно разбить на 4 уровня:

  1. PARSE ERROR
  2. FATAL ERROR
  3. WARNING
  4. NOTICE
Parse Error

Возникают, если уже на этапе проверки кода интерпретатором PHP найдена ошибка. Чаще всего это синтаксические ошибка (например, пропущенная точка с запятой). Скорее всего, такая ошибка возникла в результате последних внесенных на сайт изменений.

Что делать?

1. Если вы НЕ специалист в PHP, восстановите сайт из последней резервной копии на тот момент, когда сайт работал без ошибок.

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

Fatal Error и Warning

Возникают, если при выполнении кода какой-то его участок не может быть выполнен (например, попытка открыть несуществующий файл). Разница между 2-ым и 3-им уровнем в том, что при получении “критической ошибки” (FATAL ERROR) выполнение скрипта завершится, а при получении “предупреждения” (WARNING) — нет.

Что делать?

Восстановите сайт из последней доступной резервной копии на тот момент, когда он работал без ошибок.

Notice

К этому уровню ошибок относятся различные “замечания”, суть которых обычно отображена в тексте ошибки.

Что делать?

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

Частые ошибки PHP и их решение

 Fatal Error: Allowed Memory

Означает, что для выполнения какой-либо части кода PHP не хватает выделенной оперативной памяти. При этом лимит памяти ограничен какими-то директивами «изнутри» сайта (то есть где-либо в скриптах сайта, либо директивой memory_limit в файле .htaccess). Чтобы исправить это, измените данный лимит в большую сторону, например, в файле .htaccess.

Для этого найдите в .htaccess такую директиву:

php_value memory_limit 128M

Вместо 128M укажите желаемый размер ограничения. Обратите внимание, что символ «M» (латинская M) указывается слитно со значением.

Помните, что есть максимальные значения памяти, отведенной на выполнение скриптов PHP, предусмотенные вашим тарифом хостинга (например, на тарифах виртуального хостинга это 512 Мб, премиум — 1024 Мб). Уточните эти значения у вашего провайдера, если они не указаны явно.

Fatal Error: Out of memory

То же самое, что и предыдущая ошибка, с той разницей, что достигнут лимит памяти, заданный “снаружи”. Обратите внимание на параметр “Памяти на процесс, Мб, не более“ в условиях пользования нашим сервисом.

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

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

Unable to allocate memory for pool

Сайтам на аккаунте не хватает выделенной на тарифном плане памяти для акселераторов PHP.

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

Также, например, можно отключить акселератор APC для определенного сайта, добавив в файл .htaccess корневой директории следующую директиву:

php_value apc.cache_by_default off

Обычно имеет смысл оставлять APC для использования на самом посещаемом из ваших сайтов — это позволит использовать именно на нем преимущества акселератора, не заполняя его память данными с других, менее посещаемых сайтов.

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

Мы постараемся предложить возможные варианты решения.

Желаем вам приятной работы!

Where are PHP Errors Logged?

So when we encounter errors in our code, where exactly can we find them? At a high level, there are really only three places where PHP errors can be found: inline with program execution, in the system log, or in error monitoring tools like Rollbar.

Inline errors

By default, whenever an error or exception is thrown, PHP sends the error message directly to the user via STDOUT. In a command-line environment, this means that errors are rendered in the terminal. In a web environment, errors and exceptions get displayed directly in the browser.

While this behavior is useful for debugging problems in a development environment, it should be disabled in a production environment for security reasons. To do this, open up the PHP configuration file for the environment you are working in—typically found in a path that looks like /etc/php/:environment:/php.ini—and change the display_errors directive to Off.

; This directive controls whether or not and where PHP will output errors,  
; notices and warnings too. Error output is very useful during development, but  
; it could be very dangerous in production environments. Depending on the code  
; which is triggering the error, sensitive information could potentially leak  
; out of your application such as database usernames and passwords or worse.  
; For production environments, we recommend logging errors rather than  
; sending them to STDOUT.  
; Possible Values:  
; Off = Do not display any errors  
; stderr = Display errors to STDERR (affects only CGI/CLI binaries!)  
; On or stdout = Display errors to STDOUT  
; Default Value: On  
; Development Value: On  
; Production Value: Off  
; http://php.net/display-errors
display_errors = On

Log files

While rendering errors to STDOUT is great for debugging issues in a development environment as they happen, it isn’t very useful in a production environment. This is where the error log comes into play. By default, PHP doesn’t log any errors, which means that this value must be explicitly set. To do so, open up the same PHP configuration file referenced above in your favorite editor and find the error_log directive.

; Log errors to specified file. PHP's default behavior is to leave this value
; empty.
; http://php.net/error-log
; Example:
;error_log = php_errors.log
; Log errors to syslog (Event Log on Windows).
error_log = syslog

There are two possible values for error_log: a custom log file and the syslog. If the syslog is used, then all PHP errors will be sent directly to the default system log file—in Linux, this is typically /var/log/syslog. The more manageable method is to use a custom log file. By doing this, you can isolate your PHP application’s logs from the rest of the system logs, which can make debugging issues significantly easier.

Logging in Laravel

While PHP’s default system logger is useful for bespoke applications, it is important to note that many application frameworks provide their own built-in logging mechanisms. A great example of this is the Laravel framework. In Laravel, the logging method can be changed within the log option of the application configuration file—found in config/app.php.

/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'single'),

By default, Laravel maintains a single log file at storage/logs/laravel.log within the project directory, rather than the defined error_log option from the global PHP configuration.

Logging in Symfony

Because Laravel is built on top of Symfony, they share the same core logging mechanism—although the configuration differs between the two frameworks. Logging in Symfony and Laravel are both done using Monolog, a third-party PHP logging library that can be used to create and store logs in a large number of ways.

By default, Symfony logs are stored in var/log/dev.log and var/log/prod.log within the project directory, depending on the environment, but these defaults can be changed in the Monolog package configuration file found at config/packages/monolog.php.

$container->loadFromExtension('monolog', array(
    'handlers' => array(
        'file_log' => array(
            'type'  => 'stream',
            'path'  => '%kernel.logs_dir%/%kernel.environment%.log',
            'level' => 'debug',
        ),
        'syslog_handler' => array(
            'type'  => 'syslog',
            'level' => 'error',
        ),
    ),
));

What do PHP logs look like?

So, what exactly do PHP logs look like? In most instances, PHP logs follow a fairly predictable format:

Dec 10 04:04:38 scotchbox apache2: PHP Parse error:  syntax error, unexpected end of file in /var/www/public/index2.php on line 4

In a nutshell, the log line above can be broken up into four parts: the date, the hostname, the process, and the error message. Whenever an error is encountered or an uncaught exception is thrown, the error message is printed along with the date, hostname, and process metadata to help pinpoint what happened, where it happened, and when it happened.

A primer on log levels

It is important to note that, in PHP, there are a handful of log levels that can be squashed or raised. While these log levels are determined by PHP itself, understanding what they are and mean is a crucial step towards being able to diagnose problems as they happen.

When display_errors is set to On, it can be useful to explicitly hide and show specific log levels so you can focus on one task at a time, such as critical errors, or cleaning up warnings. This can be accomplished using the built-in error_reporting method.

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

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

This method accepts an integer value that tells PHP which errors to display, and which ones to ignore. Through the use of bitwise operators (| meaning OR, & meaning AND, and ~ meaning NOT), we can clearly and easily define which errors we want to see.

Here are a few of the most common log levels. For more information about log levels (there are quite a few of them), take a look at PHP’s official documentation.

Error Level Description
E_ERROR Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
E_WARNINIG Run-time warnings (non-fatal errors). Execution of the script is not halted.
E_PARSE Compile-time parse errors. Parse errors should only be generated by the parser.
E_NOTICE Run-time notices. These indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.

(PHP 4, PHP 5, PHP 7, PHP 8)

error_logSend an error message to the defined error handling routines

Description

error_log(
    string $message,
    int $message_type = 0,
    ?string $destination = null,
    ?string $additional_headers = null
): bool

Parameters

message

The error message that should be logged.

message_type

Says where the error should go. The possible message types are as
follows:

error_log() log types

0 message is sent to PHP’s system logger, using
the Operating System’s system logging mechanism or a file, depending
on what the error_log
configuration directive is set to. This is the default option.
1 message is sent by email to the address in
the destination parameter. This is the only
message type where the fourth parameter,
additional_headers is used.
2 No longer an option.
3 message is appended to the file
destination. A newline is not automatically
added to the end of the message string.
4 message is sent directly to the SAPI logging
handler.
destination

The destination. Its meaning depends on the
message_type parameter as described above.

additional_headers

The extra headers. It’s used when the message_type
parameter is set to 1.
This message type uses the same internal function as
mail() does.

Return Values

Returns true on success or false on failure.
If message_type is zero, this function always returns true,
regardless of whether the error could be logged or not.

Changelog

Version Description
8.0.0 destination and
additional_headers are now nullable.

Examples

Example #1 error_log() examples

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}
// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"operator@example.com");
}
// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

Notes

Warning

error_log() is not binary safe. message will be truncated by null character.

Tip

message should not contain null character. Note that message may be sent to file, mail, syslog, etc. Use appropriate conversion/escape function, base64_encode(), rawurlencode() or addslashes() before calling error_log().

kevindougans at gmail dot com

13 years ago

Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.

Sion

4 years ago

DO NOT try to output TOO LARGE texts in the error_log();

if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings, < 32 K characters) or (for insanely massive strings, about 1.6 million characters) totally crash without even throwing an error or anything (I even put it in a try/catch without getting any result from the catch).

I had this problem when I tried to debug a response from a wp_remote_get(); all of my error_log() worked as they should, except for ONE of them... (-_-)
After about a day of debugging I finally found out why & that's why I type this.

Apparently the response contained a body with over 1.6 million chars (or bytes? (whatever strlen() returns)).

If you have a string of unknown length, use this:
$start_index = 0;
$end_index = 8000;
error_log( substr( $output_text , $start_index , $end_index ) );

frank at booksku dot com

16 years ago

Beware! If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!

i dot buttinoni at intandtel dot com

15 years ago

Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)

php at kennel17 dot NOSPAM dot co dot uk

18 years ago

It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout. This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.

Matthew Swift

3 years ago

Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.

In a WordPress context, the root directory will be the site's root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin's directory in other cases. If you want all your output to go to one file, use an absolute path.

russ at russtanner dot com

3 years ago

You can easily filter messages sent to error_log() using "tail" and "grep" on *nix systems. This makes monitoring debug messages easy to see during development.

Be sure to "tag" your error message with a unique string so you can filter it using "grep":

In your code:

error_log("DevSys1 - FirstName: $FirstName - LastName: $Lastname");

On your command line:

tail -f /var/log/httpd/error_log | grep DevSys1

In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain "DevSys1".

The "-f" option means "follow" which streams all new log entries to your terminal or to any piped command that follows, in this case "grep".

SJL

15 years ago

"It appears that the system log = stderr if you are running PHP from the command line"

Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.

stepheneliotdewey at GmailDotCom

16 years ago

Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don't contain sensitive user data.

Anonymous

20 years ago

when using error_log to send email, not all elements of an extra_headers string are handled the same way. "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

<?php

error_log

("sometext", 1, "zigzag@my.domain",
"Subject: Foo\nFrom: Rizzlas@my.domain\n");?>

---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

sometext
---------------%<---------------------

quoth the docs: "This message type uses the same internal function as mail() does."

mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

php v.4.2.3, SunOS 5.8

paul dot chubb at abs dot gov dot au

15 years ago

When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
$stderr = fopen('php://stderr', 'w');
fwrite($stderr,$Message);
fclose($stderr);
}

p dot lhonorey at nospam-laposte dot net

17 years ago

Hi !

Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !

franz at fholzinger dot com

18 years ago

In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute

eguvenc at gmail dot com

14 years ago

<?php

//Multiline error log class

// ersin güvenç 2008 eguvenc@gmail.com

//For break use "\n" instead '\n'
Class log {

//

const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';

const
GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';
/*

User Errors...

*/

public function user($msg,$username)

{

$date = date('d.m.Y h:i:s');

$log = $msg." | Date: ".$date." | User: ".$username."\n";

error_log($log, 3, self::USER_ERROR_DIR);

}

/*

General Errors...

*/

public function general($msg)

{

$date = date('d.m.Y h:i:s');

$log = $msg." | Date: ".$date."\n";

error_log($msg." | Tarih: ".$date, 3, self::GENERAL_ERROR_DIR);

}

}

$log = new log();

$log->user($msg,$username); //use for user errors

//$log->general($msg); //use for general errors

?>

daniel dot fukuda at gmail dot com

14 years ago

If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.

Anonymous

2 years ago

Depending on the error, you may also want to add an error 500 header, and a message for the user:

$message = 'Description of the error.';
error_log($message);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit($message);

kazezb at nospam dot carleton dot edu

18 years ago

It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.

Robert Chapin

4 years ago

When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment. Something as simple as this might restore expected behavior:

<?php ini_set('error_log', 'error_log'); ?>

Anonymous

14 years ago

After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

http://forums.iis.net/p/1159662/1912015.aspx#1913338

1. Copy the PHP 5 binaries to "C:\php".
2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:\php"
(without the quotes) to the end.
3. Make sure that the configuration file "php.ini" resides
in the directory "C:\php" and contains the correct path
settings.
4. DELETE any old "php.ini" files from "C:\WINDOWS"
and other directories.
5. Open REGEDIT, navigate to the key
"HKLM\SOFTWARE\PHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
6. Modify NTFS security permissions of the directory
"C:\php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
7. Modify NTFS security permissions of the directories
"C:\php\session" and "C:\php\upload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
8. Navigate to the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog
\Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
9. Create or update the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog\Application\
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:

* "EventMessageFile" (REG_EXPAND_SZ) = "C:\php\php5ts.dll"

* "TypesSupported" (REG_DWORD) = 7

Понравилась статья? Поделить с друзьями:
  • Где посмотреть ошибки iis
  • Гв ошибка включения дэс
  • Где посмотреть ошибки apache
  • Где посмотреть отчет проверки диска на ошибки
  • Где находится журнал ошибок sql server