PHP Getting the last xx bytes of a large text file

by Yang Yang on April 28, 2012

Sometimes the text files are very large and you don’t want to load it in memory before searching through it because it’s inefficient. You just want to get the last few bytes of the file because the latest additions / updates are there.

This would help you:

$fp = fopen('somefile.txt', 'r');
fseek($fp, -50, SEEK_END); // It needs to be negative
$data = fgets($fp, 51);

Which gets the last 50 bytes of the file somefile.txt in $data. Thanks to niels for the solution.

Make sure the 2nd parameter for fgets() is 1 more than the absolute value of the 2nd parameter for fseek().

Comments on this entry are closed.

Previous post:

Next post: