Get last 15 lines from a large file in SFTP with phpseclib [duplicate]

天大地大妈咪最大 提交于 2019-12-23 00:51:08

问题


I want to get the last 15 lines from a large file (30MB) from a SFTP server using PHP.

I tried using the phpseclib's SFTP functionality like that:

include('./Net/SFTP.php');
$sftp = new Net_SFTP("server", 2022);
if (!$sftp->login('username', 'password')) {
    exit("Login error");
}
$size = $sftp->size('./file.txt');
$Container = nl2br($sftp->get('./file.txt', false, $size - 5000));
if( !empty($Container) ) {
    echo $Container;
} else {
    exit("empty file");
}

But this still loads in like 2 minutes for my large file.

Is it possible to get only the last X lines from a large file?


回答1:


The following should result in a blob of text with at least 15 lines from the end of the file that you can then process further with your existing logic. You may want to tweak some of the logic depending on if your file ends with a trailing newline, etc.

$filename = './file.txt'

$filesize = $sftp->size($filename);
$buffersize = 4096;

$offset = $filesize; // start at the end
$result = '';
$lines = 0;

while( $offset > 0 && $lines < 15 ) {
  // work backwards
  if( $offset < $buffersize ) {
    $offset = 0;
  } else {
    $offset -= $buffer_size;
  }
  $buffer = $sftp->get($filename, false, $offset, $buffer_size));
  // count the number of newlines as we go
  $lines += substr_count($buffer, "\n");
  $result = $buffer . $result;
}


来源:https://stackoverflow.com/questions/54335695/get-last-15-lines-from-a-large-file-in-sftp-with-phpseclib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!