Output the last lines of a file with PHP
Friday, March 11th, 2005This took me some time this morning.
For a secured part of a website I made up a log of both succesfull as failed logins.
I wanted to output the last 20 or so lines, for displaying those on a helpdesk page.
I came up with the following solution and I think it’s a elegant one:
1 <?php
2 $logbuffer = `tail -n 10 /path/to/somelog.log`;
3
4 $log_array = explode("\n", $logbuffer);
5
6 foreach ($log_array as $logline) {
7 if (!$logline == '') {
8 if (ereg('error', $logline)) {
9 echo "<span class='error'>".$logline."</span><hr />";
10 }
11 else {
12 echo "<span class='ok'>".$logline."</span><hr />";
13 }
14 }
15 }
16 ?>
17