Here is a simple way to get the last line of a file without reading the entire file into memory.
Use Linux’s Tail command to get last line of a file.
$file = escapeshellarg( '/home/bin/somefile.txt' ); $last_line = `tail -n 1 $file`;
[Update]
Here is a PHP fseek function that utilises a dynamic buffer which is more efficient than tail
on larger files – https://gist.github.com/lorenzos/1711e81a9162320fde20
Just as with
tail
, you can also get the 1st withhead
. 🙂There is a really good stackoverflow thread on this topic – http://stackoverflow.com/questions/15025875/what-is-the-best-way-in-php-to-read-last-lines-from-a-file/15025877#15025877
This function performed well, and didn’t involve the overhead of shell’ing out.
Thanks Joseph, that’s really smart! Updated post to include link to that function.