PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Debugging Your Web Application

The Debugging PHP Function

Here is the function we use to debug. Below the code, I’ll explain how it works, and then finally in this section we’ll create the log file.

Listing 5 listing-5.php
<?php
    /**
     * Write a debug message to the log file
     *
     * @param   int     $level  The debug level the message is intended for
     * @param   string  $str    The message to write
     */
    function debug($level, $str)
    {
        if (($level & DEBUG_LEVEL) && !defined('DEBUG_ABORT')) {
            if (!isset($GLOBALS['_debug_fp'])) {
                $GLOBALS['_debug_fp'] = @fopen(DEBUG_LOG_FILE, 'a+');
                if (!$GLOBALS['_debug_fp']) {
                    define('DEBUG_ABORT', 1);
                    return;
                }
                fwrite($GLOBALS['_debug_fp'], "\n\n[" . date('Y-m-d H:i:s') . '] -- MARK --' . ENDL);
            }
            fwrite($GLOBALS['_debug_fp'], '[' . date('Y-m-d H:i:s') . '] ' . $str . ENDL);
        }
    }
?>

The function basically works like this:

  • Firstly, check if the passed message needs to be logged based on the previously set DEBUG_LEVEL. This is done using the bitwise ‘AND’ operator.
  • On the first call, opens the log file for writing and saves the file pointer to the global scope
  • If the log file can’t be opened set an abort flag (DEBUG_ABORT), which tells future calls to debug() that the log file can’t be written to, so don’t even bother trying.
  • Once the file pointer is created, place a mark in the log file so separate requests can easily be tracked
  • Finally, write the debug message with a datestamp

We don’t need to worry about closing the file pointer as PHP takes care of this automatically at the end of the script execution.

Before the debug function can be used, a log file must exist, or a directory where one can be written to. Additionally, the DEBUG_LOG_FILE define must be created.

Firstly, decide where you want the file. For PhpRiot this looks like:

Listing 6 listing-6.php
<?php
    define('DEBUG_LOG_FILE', '/var/www/phpriot.com/data/logs/phpriot.log');
?>

This code can be put in the same place where the previous defines existed.

So in this case, the /var/www/phpriot.com/data/logs must be writable by the web server (e.g. chmod 707 /var/www/phpriot.com/data/logs)

In This Article