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”

One thought

  1. Kinduff ha detto:

    Nice and simple. Thanks.

Comments are closed

Recommended

Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

Test page for Bright Links plugin

To test the plugin hover your mouse to a link, or tap the link on mobile device.

Dicembre 4, 2022

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 8, 2020

Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

Settembre 2, 2016

How to add rel=”nofollow” to links with preg_replace()

Adding rel="nofollow" to external link is a good SEO practice.

Settembre 22, 2015

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

Settembre 14, 2015