Get last line of file in PHP

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

3 thoughts on “Get last line of file in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s