4

I have a text file such as a log file, and I want to get the last 50 lines from that.

How can I do it, in PHP?

Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
Roshan Wijesena
  • 3,106
  • 8
  • 38
  • 57

4 Answers4

4

I guess you could also be using "tail" if you are on linux.

$handle = popen("tail -50l YOUR_FILE_HERE 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";
    ob_flush();
    flush();
}
pclose($handle);
dwarfy
  • 3,076
  • 18
  • 22
  • BSD has them too. And I'm not sure, but I think Macs have some basic Unix utilities like those too (not like someone would run an OS X server on production, but...). – Camilo Martin Mar 17 '13 at 22:42
2

There are some sollutions in comments for function fseek.

Koc
  • 2,375
  • 2
  • 22
  • 26
2
<?
$data = file('yourfile.txt');
$lines = implode("\r\n",array_slice($data,count($data)-51,50));
?>

As simple as this

Geekbay
  • 21
  • 1
1

I think you can use fopen to get the handle, then use filesize to get the size and fseek to go to filesize-50. Then it's just fread of 50 characters to get the last 50. I imagine this ha been done before if you look at the manual under fseek.

Here is the solution in the fseek manual entry. Just change the -1 on the fseek line to -50.

Matt
  • 7,100
  • 3
  • 28
  • 58