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.
/** * 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 todebug()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:
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)




