How to log errors in PHP

Опубликовано: 26 Апрель 2026
на канале: PHP Explained
155
0

We use error_log() function to log errors in PHP. The error messages can be saved in a log file, or in a simple file, or send it in an email.

Let's start with the syntax.
There are four parameters and the first parameter is the only mandatory parameter.
Let's go through now.
error_log(message, type, destination, headers);

Parameter message
This is the error message that we are going to save in file or email.

Parameter type
Specifies where the error message should go. Here are possible values.
0 - default option. The error message should save in the system logger file. This file is set in PHP's configuration file php.ini file.
1 - message is send by email.
2 - no longer an option.
3 - message is appended to the file specified in destination.
4 - message is set directly to the SAPI logging handler.

Parameter destination
Specifies the destination of the error message.

Parameter headers
Use this parameter if type parameter set to 1 or email the message.

Now, see a few examples.
In our example, if login attempt fails, then we are saving the error message "Login failed" in the system logger file whatever it is, as it is set in php.ini file.
if (!login_success($username, $password))
{
error_log("Login failed", 0);
}

In our next example, if our searching file does not exists, then we are emailing the error message "File does not exists".
if (!file_not_exists("math.txt"))
{
error_log("File does not exists", 1, "[email protected]");
}

In this example, if user does not exists, we are saving the error message "User does not exists" in the file app_error_log.txt which is available in the application's root folder.
if (!is_user_available("john"))
{
error_log("User does not exists", 3, "app_error_log.txt");
}