Want to log script activity in your Web application, but haveno clue where to begin? Take our handy tour of PHP's logging functions,and find out how simple it really is.
Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:
<?php
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
?>
Fundamentally, logging data to a file consists of three
steps:
1. Open the target file (or create it if it doesn't already exist);
2. Append your data to the end of the file;
3. Close the file.
You can encapsulate this as a function,
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $msg . "\n");
// close file
fclose($fd);
}
?>
and then use it liberally within your code as and when
required.
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// write string
fwrite($fd, $msg . "\n");
// close file
fclose($fd);
}
$v = "Mary had a little lamb";
if (!is_numeric($v)) { logToFile("my.log", "Non-numeric variable
encountered"); }
$a = array("chocolate", "strawberry", "peach");
if (!in_array('fish', $a)) { logToFile("my.log", "No fish available"); }
$conn = @mysql_connect("localhost", "joe", "pass");
if (!$conn)
{
logToFile("my.log", "Could not connect to database");
die("Could not connect to database");
}
?>
You can make the function a little more professional by
having it automatically append the date and time of the log message to the log file as well: