kritya kritya - 1 year ago 112
PHP Question

Reading large files from end

Can I read a file in PHP from my end, for example if I want to read last 10-20 lines?

And, as I read, if the size of the file is more than 10mbs I start getting errors.

How can I prevent this error?

For reading a normal file, we use the code :

if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";

My file might go over 10mbs, but I just need to read the last few lines. How do I do it?


Answer Source

It's not pure PHP, but the common solution is to use the tac command which is the revert of cat and loads the file in reverse. Use exec() or passthru() to run it on the server and then read the results. Example usage:

$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
$currentRow = 0;
$numRows = 20;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && $currentRow <= $numRows) {
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download