ScotlandPHP 2016


(PHP 4, PHP 5)

error_loginvia un messaggio di errore


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

Invia un messaggio di errore al log del server web o ad un file

Elenco dei parametri


Il messaggio di errore che deve essere registrato.


Indica la destinazione del messaggio. I possibili tipi di messaggio sono:

error_log() tipi di log
0 message è inviato al log di sistema di PHP, utilizzando il sistema di log del Sistema Operativo o un file, a seconda di come sia impostata la direttiva di configurazione error-log.
1 message è inviato via posta elettronica all'indirizzo indicato nel parametro destination. Questo è l'unico tipo di messaggio nel quale viene usato il quarto parametro, extra_headers.
2 Non è più un'opzione.
3 message è aggiunto al file destination. Il ritorno carrello non è aggiunto automaticamente alla fine della stringa message.
4 message è inviato direttamente al gestore di log SAPI.


La destinazione. Il suo significato dipende dal parametro message_type come descritto più sopra.


Gli header supplementari. Viene usato quando il parametro message_type è impostato a 1. Questo tipo di mesaggio usa la stessa funzione interna di mail().

Valori restituiti

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Log delle modifiche

Versione Descrizione
5.2.7 Aggiunto il valore 4 per message_type


Example #1 iEsempi di uso di error_log()

// Invia notifica via log del server se non è possibile 
// connettersi al database.
if (!Ora_Logon ($username$password)) {
error_log ("Database Oracle non disponibile!"0);

// Notifica via posta elettronica all'amministratore se esauriscono i FOO
if (!($foo allocate_new_foo()) {
error_log ("Problemi seri, FOO esauriti!"1,

// un altro modo per chiamare error_log():
error_log ("Problema!"3"/var/tmp/my-errors.log");

add a note add a note

User Contributed Notes 21 notes

kevindougans at gmail dot com
6 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.
roychri at php dot net
6 years ago
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:
php at kennel17 dot NOSPAM dot co dot uk
11 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.
paul dot chubb at abs dot gov dot au
8 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');
i dot buttinoni at intandtel dot com
8 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 :)
7 years ago
If you are trying to capture PHP errors to a text file on IIS ensure that two things are set.

1) Only one error log option is set. IE:

; Log errors to specified file.
error_log = "c:\php\errorlog.txt"

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

2) The IUSR account has write and modify permissions to e rrorlog.txt .
13 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.


("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


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
8 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.
frank at booksku dot com
9 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!
p dot lhonorey at nospam-laposte dot net
10 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,"","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
eguvenc at gmail dot com
7 years ago
//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";
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
6 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.
stepheneliotdewey at GmailDotCom
9 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.
irishado at hotmail dot com
4 years ago
For beginners here is an example that will let you add audit code through your program then choose which audits get logged.  helps keep your code clean as you can add as many adit calls as you want and the configure deals with them
    // binary values
    define ("AUDIT_NORMAL",1);       // 00001
    define ("AUDIT_DB_INSERT",2);    // 00010
    define ("AUDIT_DB_UPDATE",4);    // 00100
    define ("AUDIT_DB_EXTRACT",8);   // 01000
    define ("AUDIT_DB_DELETE",16);   // 10000
    // define some types of audit level
                                     // 11110
    define ("AUDIT_ALL",31);         // all possible options
                                     // 11111
    define ("AUDIT_LEVEL",AUDIT_JUST_DB);// Choose the audit level to user
    $GLOBALS["CODEX"]= Array(1 => "Normal", 2 => "DB_INSERT", 4 => "DB_UPDATE", 8 => "DB_EXTRACT", 16 => "DB_DELETE");
    define ("LOG_PATH", "/temp/mylog");
      * Add an audit to the log
      * Some Constants Used
      * $GLOBALS["CODEX"] is an array of short descriptions for each audit type so that the log reads better.
      * use and AND statement to compare the type of information you are wanting to audit and the level that you have told your program to record
      *  type, level 
      *  AUDIT_NORMAL    & AUDIT_LEVEL  = 00000  ie 00001 & 11110 === 00000  ( Do not log )
      *  AUDIT_DB_UPDATE & AUDIT_LEVEL  = 00100  ie 00100 & 11110 === 00100  ( Add to log )
      *  AUDIT_DB_INSERT & AUDIT_LEVEL  = 00010  ie 00010 & 11110 === 00010  ( Add to log )
      *  So when you AND a interger with a MASK in this case the AUDIT_LEVEL
      * @access public
      * @author IrishAdo <>
      * @param String Class you were in
      * @param String Type of Audit information
      * @param String Message
    public function __AddAudit($class, $typeof, $msg){
        if ((AUDIT_LEVEL & $typeof)*1 === $typeof && AUDIT_LEVEL != AUDIT_NONE){
            $path = LOG_PATH . date("Ymd.H") . ".audit.log";
            $fp = fopen($path ,"a");
                $usr = $_SESSION["name"];
                $ip   = $_SERVER["REMOTE_HOST"];
                $file = $_SERVER["SCRIPT_NAME"];
                fwrite($fp, "". $GLOBALS["CODEX"][$typeof]."\t" . Date("r") . "\t$ip\t$file\t$class\t$usr\t$msg\r\n");
            } else {
                print "Unable to write to file $path.";
franz at fholzinger dot com
11 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
kazezb at nospam dot carleton dot edu
11 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.
marques at displague dot com
11 years ago
Beware the size of your custom error_log!

Once it exceeds 2GB the function errors, ending your script at the error_log() line.  I'm sure this differs from OS to OS, but I have seen it die writing to ext2 under modern Linux systems.
6 years ago
This had me hunting for a while till I figured this out.  What ever folder you want your logs deposited to, don't create the log file yourself, let php do it for you.  For some reason, if the log file already exists and it's 0 KB, PHP will try to re-create the log file and fail in the process.  It never attempts to write to the pre-existing empty file, just fails on folder creation.  Might be do to the folder permissions I have on windows, but this is what I found with read/write/modify permissions for IIS_IUSRS on Win2008.  Once PHP has written to its self-created file successfully, it will append to the file on new errors.  Process Monitor is my friend :)
larry.kooper at gmail dot com
8 years ago
On a Mac running OS X, for the error logging to work I needed to put this in my php.ini:
error_log = /tmp/php_errors.log
Attempting to put the log in other locations did not work, probably due to permission issues.
7 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:

   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
Scott R
6 years ago
When starting Apache from a user context other than Apache's runtime user, the error log file (if one is specified) may be created under the starting user if it did not previously exist.

For example, I had specified the incorrect filename for my browscap.ini file, and would only see this error in the log file upon each restart of Apache.  Because of this, I assumed I'd configured logging correctly:

[24-Feb-2010 12:33:04] PHP Warning:  Cannot open '/etc/php5/apache/lite_php_browscap.ini' for reading in Unknown on line 0

No other errors would log at runtime even though I had originally set the owner of the log directory to www-data (Apache runs under this user context).  My file (error.log) was being created with the owner = root, because I had restarted the apache2 service as root after configuring the log file location.  (I made the poor assumption that since PHP/Apache had created the file it was created by www-data, so I hadn't looked).

Changing owner of the log file to the correct user (i.e. www-data) fixed the problem.
To Top