info: Any information that you wish to be stored in the log
Such as information about any error that may have occoured
script: Which script triggered the log event, defaults to the contents
of $_SERVER['PHP_SELF']. If the log event is being called from
within a file that has been included, set this value to __FILE__
else use $_SERVER['PHP_SELF'] or ignore this parameter
This example will log the clients user-agent, as sent by the browser, to the
file 'log.txt', and will use the default value for $script ($_SERVER['PHP_SELF'])
*/
function log_event($file, $info, $script = "")
{
//Get the IP of the computer that triggered the log event
$ip = $_SERVER['REMOTE_ADDR'];
//Get the time that the log event was triggered
$time = time();
//Work out what script called the log event
//This is needed because variables cannot be used as default values in a function
if($script == "")
{
$script = $_SERVER['PHP_SELF'];
}
//Build the log string containing logged IP, time, script and event information
$string = "$ip - $time - $script - $info\r\n";
//Open the log file for writing (or create and open it if it does not exist)
if(!$f = fopen($file, "a")) return FALSE;
//Write to the log file
if(!fwrite($f, $string)) return FALSE;
//Close the logfile
fclose($f);
//Return a value of TRUE to indicate that the function has finished successfully
return TRUE;
}
?>
The example script, that calls the logger
<?PHP
//Include the event logger script
include('event_logger.php');
//Log the users user agent (as reported bu the browser) to the file log.txt
log_event("log.txt", $_SERVER['HTTP_USER_AGENT']);