(PHP 4, PHP 5, PHP 7)

error_logОтправляет сообщение об ошибке заданному обработчику ошибок


bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )

Отправляет сообщение об ошибке в лог web-сервера или в пользовательский файл.

Список параметров


Сообщение об ошибке которое должно быть логировано.


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

error_log() log types
0 Сообщение message отправляется в системный регистратор PHP, используя механизм логирования операционной системы, или файл, в зависимости от значения директивы error_log в конфигурационном файле. Это значение по умолчанию.
1 Сообщение message отправляется электронной почтой на адрес, установленный в параметре destination. Это единственный тип сообщения, где используется четвертый параметр extra_headers.
2 Больше не используется.
3 message применяется к указанному в destination файлу. Перенос строки автоматически не добавляется в конец message.
4 Сообщение message отправляется напрямую в обработчик логера SAPI.


Назначение. Устанавливается в зависимости от параметра message_type.


Дополнительные заголовки. Используется, когда значение параметра message_type - 1. Данный тип сообщения использует ту же внутреннюю функцию, что и mail().

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.



error_log() не является бинарнобезопасным. message обрезается по null-символу.


message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog, и т.д.. Используйте подходящую преобразующую или экранирующую функцию, base64_encode(), rawurlencode() или addslashes() перед вызовом error_log().


Пример #1 Примеры использования error_log()

// Отправляет уведомление посредством серверного лога, если мы не можем 
// подключиться к базе данных.
if (!Ora_Logon($username$password)) {
error_log("Oracle database not available!"0);

// Уведомить администратора электронной почтой,  если невозможно выделить ресурсы для FOO
if (!($foo allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!"1,

// другой способ вызвать error_log():
error_log("You messed up!"3"/var/tmp/my-errors.log");

Список изменений

Версия Описание
5.2.7 Добавлен 4-й тип значения в message_type.


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.


"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


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
2003-03-28 16:14:56
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
2005-04-20 12:21:16
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.
2005-07-21 13:39:58
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.
2005-07-25 17:04:24
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,"","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
2006-08-28 06:33:27
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!
2006-11-02 17:28:19
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.
2007-06-26 21:05:55
"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.
2007-12-31 20:16:10
Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit). 
A work aorund is rotate logs :)
2008-02-16 05:32:22
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'); 
2008-06-17 01:37:46
//Multiline error log class
// ersin güvenç 2008
//For break use "\n" instead '\n'

Class log {
const USER_ERROR_DIR '/home/site/error_log/Site_User_errors.log';
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";
   General Errors...
public function general($msg)
$date date('d.m.Y h:i:s');
$log $msg."   |  Date:  ".$date."\n";
error_log($msg."   |  Tarih:  ".$date3self::GENERAL_ERROR_DIR);


$log = new log();
$log->user($msg,$username); //use for user errors
//$log->general($msg); //use for general errors
2008-10-28 10:03:27
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:

   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 
   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 
   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 
\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 
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
2009-08-26 13:22:34
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.
2009-09-01 08:42:43
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.
2010-02-24 04:19:13
There is a limit on the maximum length that you can pass as the $message.

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of 'log_errors_max_len'.

More details here:
2010-04-25 12:02:55
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'); ?>
2018-10-04 02:31:03
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 ) );
2018-10-18 17:48:04
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.
2019-11-05 15:32:53
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".
2019-11-22 23:10:28
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.';
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
2020-11-06 22:41:59

    Поддержать сайт на родительском проекте КГБ