Skip to content
PHP Logo

How can errors be automatically logged to a file in PHP?

To automatically log errors to a file in PHP, you can use the `set_error_handler` function to define a custom error handler that logs errors to a file. Within the custom error handler function, you can use functions like `error_log` to write errors to a specified file.

php
// Define custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $errorLog = "Error: [$errno] $errstr in $errfile on line $errline";
    error_log($errorLog, 3, "error.log"); // Write error to file
}

// Set custom error handler
set_error_handler("customErrorHandler");

// Trigger a sample error to test
trigger_error("This is a sample error", E_USER_ERROR);