How can an error handler be implemented in PHP to redirect output to a file for easier debugging?

When an error occurs in PHP, it can be helpful to redirect the error output to a file for easier debugging. This can be achieved by setting up a custom error handler function that captures the error message and writes it to a log file. By redirecting the error output to a file, developers can easily track and troubleshoot issues in their code.

// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $error_message = "Error: [$errno] $errstr in $errfile on line $errline\n";
    error_log($error_message, 3, "error.log"); // Write error message to a log file
}

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

// Trigger a sample error
$undefined_variable = $undefined_variable + 1;