tail functionality in PHP
Posted on 12th June 2008 in PHP |
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.




















4 Responses
This script is really useful. Thanks.
Thank you very much. I modified slightly the code for letting the user change the number of lines using a GET variable.
You may want to check if the file exists before you try to read it.
Absolutely. You are welcome to modify as Fjor has already quite rightly done it.