How to write errors and warnings to a file in php?

PHP

Approach 1:The error_log() function can be used to send error messages to this file. The first argument to the function is the error message to send. The second argument tells where to send / write the error message. In this case, the second argument is 3 and is used to redirect the error message to a file. The third argument is used to specify the path to the error log file.Below is the implementation of the above approach:
// php code for registering an error in a given file 
// error message for registration $error_message = "This is an error message!" ;  
// path to the log file where errors should be logged $log_file = "./ my-errors. log " ;  
// write an error message to this log file error_log ( $error_message , 3, $log_file );  
?>
Output:
[20-Dec-2018 17:32:00 UTC] This is an error message! 
Approach 2:
  • The init_set() function allows the user to programmatically update the configuration of the php.inifile.
  • The ini_set ("log_errors", TRUE) command can be added to the php script to enable error logging in php.
  • The command ini_set (' error_log & # 39 ;, $log_file) can be added to the php script to setting the error log.
  • Further call the error_log ($error_message) function can be used to write an error message to this file.
Below is the implementation of the above approach:
// PHP code to log an error in the given f aile 
// error message for registration $error_message = "This is an error message!" ;  
// path to the log file where errors should be logged $log_file = "./ my-errors. log " ;  
// set error logging to active ini_set ( "log_errors" , TRUE);  
// set the log file to php.ini ini_set ( 'error_log' , $log_file );  
// logging the error error_log ( $error_message ) ;  
?>
Output:
[20-Dec-2018 17:30:35 UTC] This is an error message! 
Similar approach:The following lines can also be added directly to php.ini,to make configuration changes permanent for every php script that logs errors and warnings.
log_errors = on error_log = ./errors.log 
Note:this approach is not very robust compared to other approaches. Approach 1 is better because it gives you the flexibility to select different files to register at the same time without changing the configuration of the php.inifile.



Get Solution for free from DataCamp guru