Re: Read Last Lines of a Text File

From: Date: Wed, 16 Jun 2004 20:20:01 +0000
Subject: Re: Read Last Lines of a Text File
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-188433@lists.php.net to get a copy of this message
srmiller@interbel.net (Scott Miller) wrote in news:001101c453cc$c5b20ab0$617b1c0a@ScottTower: > I have a text file (log file) that I want to be able to read the last > 30 or 40 lines of. I've created the code below, but since this file > is so large (currently 8 MB) it won't work. The code works on smaller > files, but not this one. Can someone look at this below and tell me > where I went wrong? > > <?php > > $filename ="/var/log/radius.log"; > > $myFile = fopen($filename, "r"); //open the file for reading, file > pointer will be at the beginning of the file > > if(! $myFile){ // Make sure the file was opened > successfully > > print ("File could not be opened."); > > exit; > } > > $fcontents = file($filename); > > $limit = 30; > > for ($i = 0; $i < $limit; $i++){ // while $i is less than 30 > > $line = $fcontents[$i]; // assign value of array element to a > variable > > if($line != ""){ // if the line from the file is not blank > print it > echo "$line \n"; > } > > } > > fclose($myFile); > > ?> > > Thanks, > Scott Miller > > > Your problem is likely with the following line, which reads the *entire* file into an array: $fcontents = file($filename); You're also opening and closing a file handle, but never using it. Use fread after fopen instead of the "file" function. You'll have to decide on a byte limit instead of a line limit, though. http://php.net/manual/en/function.fread.php

« previous php.general (#188433) next »