Similar: How to read only the last 5 lines of a text file in PHP?
I have a large log file and I want to show 100 lines from position X in the file. I need to use fseek, not file(), because the log file is too large.
I have a similar function, but it will only read from the end of the file. How can it be changed so that you can specify the starting position? I will also need to start at the end of the file.
function read_line($filename, $lines, $revers = false)
{
$offset = -1;
$i = 0;
$fp = @fopen($filename, "r");
while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) {
$c = fgetc($fp);
if($c == "\n" || $c == "\r"){
$lines--;
if($revers){
$read[$i] = strrev($read[$i]);
$i++;
}
}
if($revers) $read[$i] .= $c;
else $read .= $c;
$offset--;
}
fclose ($fp);
if($revers){
if($read[$i] == "\n" || $read[$i] == "\r")
array_pop($read);
else $read[$i] = strrev($read[$i]);
return implode('',$read);
}
return strrev(rtrim($read,"\n\r"));
}
What I'm trying to do is create a web-based log viewer that starts at the end of the file and displays 100 lines, and when you click Next, the next 100 lines will be shown preceding this.
source
share