Mini log functions for PHP

When  you have to log something with php you can use fopen to create  a file and then use fwrite…

Febbraio 20, 2012

When  you have to log something with php you can use fopen to create  a file and then use fwrite to write strings… it’s quite easy. But, if you want some small functions to add to your most used “common.php” file, you can add this fours small functions:

/* MINI LOG SYSTEM */

function openLog($filename) {
 $f = fopen($filename,'a+');
 return $f;
}

function writeLog($f,$s) {
 $s = date("Y-m-d H:i:s")." ".$_SERVER['REMOTE_ADDR']." ".$_SERVER['HTTP_USER_AGENT']." ".$s."\n";
 fwrite($f,$s);
}

function readLog($f) {
 fseek($f,0,SEEK_END);
 $size = ftell($f);
 fseek($f,0);
 return fread ($f, $size);
}

function closeLog($f) {
 fclose($f);
}

OPEN LOG
Use the openLog to create the log file (be sure to have permission to write on that directory), this function returns the pointer to the file. So you have to store the result on a variable to pass it in the next calls.

WRITE LOG
Use the writeLog function to write a free string to the log file. User agent, ip address and date and time are added automatically.

READ LOG
Use this function to read the content of the log file.

CLOSE LOG
Use this function to close the log file.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “Mini log functions for PHP”

Just one thought

  1. Kinduff ha detto:

    Nice and simple. Thanks.

Comments are closed