Reading large files from end

前端 未结 10 1543
慢半拍i
慢半拍i 2020-12-28 19:47

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 erro

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 20:14

    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:

     /tmp/myfilereversed.txt";
    exec($command);
    $currentRow = 0;
    $numRows = 20;  // stops after this number of rows
    $handle = fopen("/tmp/myfilereversed.txt", "r");
    while (!feof($handle) && $currentRow <= $numRows) {
       $currentRow++;
       $buffer = fgets($handle, 4096);
       echo $buffer."
    "; } fclose($handle); ?>

提交回复
热议问题