Logging With PHP - The Bare Necessities
(Page 2 of 9 )
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:
<?php
function logToFile($filename, $msg)
{
// open file
$fd = fopen($filename, "a");
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
}
?>
Here's an example of the output:
[2002/11/25 06:02:42] Non-numeric variable encountered [2002/11/25
06:02:42] No fish available [2002/11/25 06:02:43] Could not connect to
database
Next: Turning The Tables >>
More PHP Articles
More By icarus, (c) Melonfire