Thursday, February 8, 2024

[SOLVED] How to write browser output to log file using PHP?

Issue

I have the script is which runned by Cron jobs. So, while it runs, I can't see what output of the task is. (errors and so on.)
So I need to write browser output to log file using PHP. How can I do this ?


Solution

I use this script for error logs:

// Destinations
define("ADMIN_EMAIL", "[email protected]");
define("LOG_FILE", "/my/home/errors.log");
 
// Destination types
define("DEST_EMAIL", "1");
define("DEST_LOGFILE", "3");
 
/**
  * my_error_handler($errno, $errstr, $errfile, $errline)
  *
  * Author(s): thanosb, ddonahue
  * Date: May 11, 2008
  * 
  * custom error handler
  *
  * Parameters:
  *  $errno:   Error level
  *  $errstr:  Error message
  *  $errfile: File in which the error was raised
  *  $errline: Line at which the error occurred
  */
 
function my_error_handler($errno, $errstr, $errfile, $errline)
{  
  switch ($errno) {
    case E_USER_ERROR:
      // Send an e-mail to the administrator
      error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
 
      // Write the error to our log file
      error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
      break;
 
    case E_USER_WARNING:
      // Write the error to our log file
      error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
      break;
 
    case E_USER_NOTICE:
      // Write the error to our log file
      error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
      break;
 
    default:
      // Write the error to our log file
      error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
      break;
  }
 
  // Don't execute PHP's internal error handler
  return TRUE;
}
 
 
// Use set_error_handler() to tell PHP to use our method
$old_error_handler = set_error_handler("my_error_handler");

It gives full control over what actions to take when an error is raised.
Taken directly from Web Services Wiki of Stanford University



Answered By - Valeh Hajiyev
Answer Checked By - David Marino (WPSolving Volunteer)