Logging processes with PHP

Logging processes with PHP

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on November 23, 2009

Its sometimes necessary as a developer to log and track data as it is processed either to debug or to keep a simple record of maybe who’s logged in or out of your site. You could easily do this by accessing a MySQL database and adding a row, but you then have to create and maintain that database. So today I’m going to run through the steps to writing and reading a .txt log file.

The Code

In order to write and access our log file we will be using the php functions fopen() fwrite() and fclose(). find below the rules that can be passed to fopen().

Rule Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.

NOTE: It’s important that the file permissions for the log file are set so our script can access and modify it.


function log_action($message="") {
			$logfile = 'logs/log.txt';
			$new = file_exists($logfile) ? false : true;
		        if($handle = fopen($logfile, 'a')) { // append
			$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
		        $content = "{$timestamp} | {$message}\n";
			fwrite($handle, $content);
			fclose($handle);
			if($new) { chmod($logfile, 0755); }
		  } else {

			echo "Could not open log file for writing.";

		  }
	}

Running the function

In a real application situation we could use logging to track certain aspects of an applications process, for example if I had a video upload script that sends a request to an API to encode the video once it’s uploaded, then puts some data in the database, we could log at each stage of the process to check that each stage was completed successfully and that the script didn’t error out.

Below is a very simple example of how to call the function.


$message = 'Posted to the database';
	log_action($message);

Reading our log file

log
Above is an image example of the code below minus the row highlighting and thumbnails.

Below is a quick method for displaying the contents of our log file. You can see that the data is displayed in a table for readability. in order to get each line of data we use fgets(); which will get each individual row from our log file, then using the PHP explode() function we can save the data in an array so we can then echo it in the individual table cells.

<table border="0" width="960px" cellpadding="4" cellspacing="0" style="font-family:Arial, Helvetica, sans-serif; font-size:14px;" class="pag">
  <tr style="background:#FFFFCC;">
     <td style="border-bottom:3px solid #FFCC99;">Datetime</td>
    <td style="border-bottom:3px solid #FFCC99;">Video Id</td>
    <td style="border-bottom:3px solid #FFCC99;">Stage</td>
    <td style="border-bottom:3px solid #FFCC99;">Status</td>
  </tr>
<?php
$filename = 'logs/log.txt';
$fp = fopen($filename, "r");
if($fp)
{ 

   while(!feof($fp))
   {
      $line = fgets($fp);
$data = explode('|', $line);

  echo '<tr>
     <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[0].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[1].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; border-right:1px solid #ccc;"">'.$data[2].'</td>
    <td style="padding:5px; border-bottom:1px solid #ccc; ">'.$data[3].'</td>
  </tr>';

   }
}
else
{
  echo ' unable to open file for reading ';
}
?>
</table>
More tutorials from Papermashup
Comments
9 discussions around Logging processes with PHP
  1. chiiaee says:

    help me plz……i cant writing log file .text and cant logined page.?

  2. rubbish says:

    I disagree wit Singh… this is a very good and simple logging process that is portable PRECISELY because it doesnt require or use a monolithic library with a huge learning curve of features before you get started!

    The only caveat I would bear in mind is to put sufficient delimiters in your output stream that would enable you to either load it into a database if you decide you need to, or to scan /search for some text or condition easily.

    Using this feature in conjunction with the TAIL utility in linux will allow you to specify the last ‘n’ lines of the file

    http://tekkie.flashbit.net/php/tail-functionality-in-php

  3. I would recommend PHP starters not to go into this type of logging, instead use available libraries like http://pear.php.net/package/Log

  4. Enatom says:

    Great. This blog post is not just about showing of new skills… its about reminding people what is and could be important.. you see, i hadn’t thought of logging data like this, whereas before i had to wrap my head around a database for almost everything…

    again this is noted down on the to do list.

  5. Ben says:

    Nice idea. I did a similar thing but with an XML file. Thats my prefered method but it’s all the same really.

  6. Anyone with PHP5 can use file_put_contents(), which gets rid of all the fopen, fwrite, fclose stuff in the log function.

  7. SeanJA says:

    Or better yet, use a php extension that does the logging for you? No use reinventing the wheel…

    http://pear.php.net/package/Log

    • Ashley says:

      @SeanJA this is an example for beginners on how to understand and use php logging whilst using the fopen() technique, i don’t feel it’s reinventing the wheel, rather exploring the technology and experimenting with different techniques. Thanks for the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.