-1

I want a way to write the errors and warnings in PHP script or the output of the script for example echo "Hello World"; in Text File
I don't think error_log() function is useful in my case because this function is logging the errors that I previously mentioned in my code.

What I want is something like this
PHP Code

<?php

echo "Your Name is ".$name; // $name here is not defined 

?>

This script will give the following error
Notice: Undefined variable: name in C:\wamp64\www\example.php on line 3

This error will be written in php_error.log automatically in my server, but I want to write this error in separated text file.

Nasser Hajlawi
  • 313
  • 2
  • 15

1 Answers1

0

You can do this with a custom error handler that you set with the set_error_handler function

<?php

function handleError($errorNumber, $errorString, $errorFile, $errorLine, array $errContext)
{
    // Path to log file
    $logFilePath = 'errors.log';

    // Do we want to prevent the default PHP error handler from executing?
    $allowDefaultLogging = true;

    // error was suppressed with the @-operator do not log and cancel the default error handler
    if (0 === error_reporting())
    {
        return false;
    }

    // Build log message string from error components
    $message = $errorFile . ':' . $errorLine . ' errno ' . $errorNumber . ' ' . $errorString . PHP_EOL;

    // Open the file for writing, append, create file if it does not exist
    $logHandle = fopen($logFilePath, 'a+');

    // Write the error message
    fwrite($logHandle, $message);

    // Close the file handle
    fclose($logHandle);

    // Tell PHP whether or not to handle the error with the default handler
    return $allowDefaultLogging;
}

// Tell PHP we want errors to go to our custom handler
set_error_handler('handleError');

echo "Your Name is " . $name . PHP_EOL; // $name here is not defined
Rob Ruchte
  • 3,569
  • 1
  • 16
  • 18