Hi,

I need to create a simple PHP script that writes php errors (Warning notices etc.) to a text file (no MySQL necessary). I know PHP has a built in error log function but the examples given in the manual are too complex. Any ideas where I could start?

I already have error reporting enabled at the start of my scripts,

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
?>

But I need a way of capturing the error messages in a log. Any ideas where I could start?

Thanks!

Peter.

    Hi,

    I was thinking about something like this...

    <?php
    // Enable error reporting
    ini_set('display_errors', 1);
    error_reporting(E_ALL & ~E_NOTICE);
    
    // Tell php where your custom php error log is
    ini_set('error_log', 'php-error.log');
    
    // Try to do something that will generate an error, like opening a file that doesn't exist
    $file=fopen('welcome.txt','r');
    
    // Append the error message to the php-error log
    error_log($php_error_msg);
    ?>

    🙂

    P.

      If you are trying to capture errors to a log file, then you need 2 steps:
      1. set an error handler callback
      2. write the callback implementation

      http://us3.php.net/manual/en/function.set-error-handler.php

      Then my callback implementation would basically call this:
      http://us3.php.net/manual/en/function.error-log.php

      In the end, I think its the same as your approach.

      // set up an error log, you'd probably keep this under lock and key rather than in /tmp
      define('MY_ERR_LOG_FILE', '/tmp/php-error.log');
      // register callback to capture error msgs
      set_error_handler('my_error_logger');
      // implement the callback
      function my_error_logger($errno, $errstr, $errfile, $errline, $errctx)
      {
          $date = date("Y-m-d H:i:s");
          $msg = "[$date] $errno: $errst in $errfile at line $errline\n";
          error_log($msg, 3, MY_ERR_LOG_FILE);
      }
      

        You could also use PHP's error log. Two settings in php.ini:

        ; Log errors into a log file (server-specific log, stderr, or error_log (below))
        ; As stated above, you're strongly advised to use error logging in place of
        ; error displaying on production web sites.
        log_errors = On
        
        ; Log errors to specified file.
        error_log = /insert/path/to/logfile.here
        

        And maybe a third:

        ; Print out errors (as a part of the output).  For production web sites,
        ; you're strongly encouraged to turn this feature off, and use error logging
        ; instead (see below).  Keeping display_errors enabled on a production web site
        ; may reveal security information to end users, such as file paths on your Web
        ; server, your database schema or other information.
        display_errors = Off
        
          Write a Reply...