Re: Reading log files.

From: Date: Tue, 05 Feb 2002 04:16:30 +0000
Subject: Re: Reading log files.
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-83514@lists.php.net to get a copy of this message
On Mon, 2002-02-04 at 19:22, Jared wrote: > I am creating a script that reads "Radius" log files and prints them to > the browser. I want the User to be able to specify the Number of lines > they want to see beginning at the end of the file and going up instead > of reading the lines at the beginning (Which I can do). > Does anyone have an idea on how to do this? > > Thanks in Advanced Jared I came up with two little routines for this sort of thing. The one using arrays is faster on small files; the one using fseek() is much, much faster on big files. Take your pick: <?php function tail($filename, $lines) { /* Read file into an array. */ $text = file($filename); /* Move to the last line. */ end($text); /* Back up until we're the right number of lines from the end. */ for ($i = 1, $cnt = count($text); $i < $lines && $i <= $cnt; $i++) { prev($text); } /* Now just dump them. */ while (list(, $line) = each($text)) { echo $line; } } function tail($filename, $lines) { /* Open and position the pointer at the end of the file. */ $fp = fopen($filename, 'r'); fseek($fp, 0, SEEK_END); $filesize = filesize($filename); $nls = 0; $i = 1; while ($nls < $lines && $i < $filesize) { if (($char = fgetc($fp)) === "\n") { $nls++; } fseek($fp, -2, SEEK_CUR); $i++; } $text = ''; while (!feof($fp)) { $text .= fgets($fp, 4096); } echo $text; fclose($fp); } ?> Hope this helps, Torben -- Torben Wilson <torben@php.net> http://www.thebuttlesschaps.com http://www.hybrid17.com http://www.inflatableeye.com +1.604.709.0506

« previous php.general (#83514) next »