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…

February 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:


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";

function readLog($f) {
 $size = ftell($f);
 return fread ($f, $size);

function closeLog($f) {

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.

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

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

Use this function to close the log file.


I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of and and I'm actually the Chief Technical Officer of Better Days web agency.

Comments on “Mini log functions for PHP”

One thought

  1. Kinduff says:

    Nice and simple. Thanks.

Comments are closed


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…

September 2, 2016

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

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

September 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…

September 14, 2015

Reordering rows records on a mysql table with PHP

This PHP function lets you reorder records on a table when you have a field used for save the position.…

December 18, 2013

Scraping content with PHP as if it was jQuery

Building a spider or a bot needs some knowledge of regular expressions, you must know and use preg_match or preg_match_all…

December 8, 2013

Embedding images in HTML or CSS with PHP

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of…

December 4, 2013