Papermashup

Subscribe


Tweets


"RT @bethgordon: .@Tesco Please rethink archaic 'Approved by Mums'. Pretty sure it's not just mothers who make childcare decisions. https://…"

@ashleyford 3 hours ago

"Is there ever a time that @DFS doesn't have a sale on?"

@ashleyford 4 days ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Logging processes with PHP

AshleyAshley

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().

RuleDescription
‘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>

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 9
  • chiiaee
    Posted on

    chiiaee chiiaee

    Reply Author

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


  • rubbish
    Posted on

    rubbish rubbish

    Reply Author

    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


  • Abhinav Singh
    Posted on

    Abhinav Singh Abhinav Singh

    Reply Author

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


  • Enatom
    Posted on

    Enatom Enatom

    Reply Author

    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.


  • Ben
    Posted on

    Ben Ben

    Reply Author

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


  • Adam Scheinberg
    Posted on

    Adam Scheinberg Adam Scheinberg

    Reply Author

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


  • SeanJA
    Posted on

    SeanJA SeanJA

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @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.


  • SeanJA
    Posted on

    SeanJA SeanJA

    Reply Author

    Why not use the fgetcsv instead? http://php.net/manual/en/function.fgetcsv.php