PHP: Hypertext Preprocessor This little PHP code snippet could come in handy for those in a need to display most recent entries in a considerably heavy text file, e.g. Apache log.

In UNIX environments there’s tail, that does the trick of displaying last few lines in a text file, e.g.

tail -n 10 /home/clients/tekkie.flashbit.net/logs/default-error.log

for the last 10 lines of Apache error log. On the remote server this kind of tool is the subject of SSH access or the possibility of using proc_open or exec functions of PHP to call tail. Mostly, esp. on the virtual servers, this is not the case.

The above reasoning is exactly why this code is a handy tool:

< ?php
 
// full path to text file
define("TEXT_FILE", "/home/www/default-error.log");
// number of lines to read from the end of file
define("LINES_COUNT", 10);
 
 
function read_file($file, $lines) {
    //global $fsize;
    $handle = fopen($file, "r");
    $linecounter = $lines;
    $pos = -2;
    $beginning = false;
    $text = array();
    while ($linecounter > 0) {
        $t = " ";
        while ($t != "\n") {
            if(fseek($handle, $pos, SEEK_END) == -1) {
                $beginning = true; 
                break; 
            }
            $t = fgetc($handle);
            $pos --;
        }
        $linecounter --;
        if ($beginning) {
            rewind($handle);
        }
        $text[$lines-$linecounter-1] = fgets($handle);
        if ($beginning) break;
    }
    fclose ($handle);
    return array_reverse($text);
}
 
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
 
echo "<strong>".TEXT_FILE."</strong>\n\n";
echo "File size is {$fsize} megabytes\n\n";
echo "Last ".LINES_COUNT." lines of the file:\n\n";
 
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
    echo $line;
}
?>

Download the code.

Share and bookmark:

  • Technorati
  • StumbleUpon
  • Digg
  • Facebook
  • Google
  • del.icio.us
  • Mixx
  • blinkbits
  • blogmarks
  • Blogsvine
  • Furl
  • Live
  • NewsVine
  • Reddit
  • Slashdot
  • LinkedIn
  • Pownce
  • Webride