12.5. Logging

If an attacker successfully obtains the necessary information to log in to someone else's account, then any actions they perform look like they are legitimate even though they are not. At best with careful logging and monitoring you may be able to identify and stop some of these attacks in their tracks. At worst, hopefully you have enough information in your logs to roll back any changes an attacker made. Logging is important. It doesn't have to be complex to be effective, either.

The following code can be used to record database updates to a log file:

// specify log file
define('LOGFILE', '/srv/apache/example.com/logs/database.log');

// define group and record separator characters
define('GS', chr(0x1D));
define('RS', chr(0x1E));

// begin or continue session

// write the provided message to the log file
function write_log($message)
    $fp = fopen(LOGFILE, 'a');
    fwrite($fp, date('Ymd\THis') . $_SESSION['username'] . GS . $message . RS);

Log entries are separated by an end of record character (RS, character code 0x1E). Each entry starts with a fixed-width character string, which represents a timestamp in ISO-8601 format followed by the username of the person who issued the call. The timestamp will always be 15 characters in length but the length of the username can vary so the group separator (GS, character code 0x1D) is used to terminate it. The final entry of the record is the log message (which will be the SQL statement executed ...

Get PHP and MySQL®: Create-Modify-Reuse now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.