How to Log Errors and Warnings in a File with PHP

PHP allows logging errors and warnings into a file with the help of a php file and modifying the configuration the php.ini file configuration.

Below, we will consider two methods to achieve that.

Watch a course Learn object oriented PHP

Using the error_log() Function

This function is used for sending error messages to a particular file. The first argument of the function is the error message that is going to be sent. The second argument sets the place for logging the error message (3 to save into the file, 1 to send an email). The aim of the third argument is to indicate the file path of the error logging file.

Now, let’s check out an example of using error_log():

<?php
// php code for logging error into a given file

// error message to be logged
$error_message = "It is an error message!";

// path of the log file where errors need to be logged
$log_file = "./my-errors.log";

// logging error message to given log file
error_log($error_message, 3, $log_file);

?>

Using the ini_set() Function

With the help of the ini_set() function, you can upgrade the configuration of your php.ini file.

This function includes several handy commands:

  • The ini_set("log_errors", TRUE) command is added to the php script for enabling error logging in PHP.
  • The ini_set("error_log", $log_file) command is added to the script for setting the error logging file.
  • The error_log($error_message) command is applied for logging an error message to a particular file.

Here is an example of this approach:

<?php
// PHP code to log error into a given file

// error message to be logged
$error_message = "This is an error message!";

// path of the log file where errors need to be logged
$log_file = "./my-errors.log";

// setting error logging to be active
ini_set("log_errors", true);

// setting the logging file in php.ini
ini_set('error_log', $log_file);

// logging the error
error_log($error_message);

?>
Before using this approach, note that it is not highly reliable on the contrary to the first approach. So, it is more recommended to use the 1st method as it allows you to choose different files at the same time without changing the php.ini file configuration.