php - 使用 PHP 和 Guzzle 流式传输远程文件

标签 php streaming guzzle

我的应用程序应该将一个大文件流回浏览器,即远程服务器。目前,该文件由本地 NodeJS 服务器提供。

我正在使用 25GB 的 VirtualBox 磁盘镜像,只是为了确保它在流式传输时没有存储在内存中。
这是我正在努力的相关代码

    require __DIR__ . '/vendor/autoload.php';
    use GuzzleHttp\Stream\Stream;
    use GuzzleHttp\Stream\LimitStream;

    $client = new \GuzzleHttp\Client();
    logger('==== START REQUEST ====');
    $res = $client->request('GET', 'http://localhost:3002/', [
      'on_headers' => function (\Psr\Http\Message\ResponseInterface $response) use ($res) {
        $length = $response->getHeaderLine('Content-Length');
        logger('Content length is: ' . $length);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="testfile.zip"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . $length);

      }
    ]);

    $body = $res->getBody();
    $read = 0;
    while(!$body->eof()) {
      logger("Reading chunk. " . $read);
      $chunk = $body->read(8192);
      $read += strlen($chunk);
      echo $chunk;
    }
    logger('Read ' . $read . ' bytes');
    logger("==== END REQUEST ====\n\n");

    function logger($string) {
      $myfile = fopen("log.txt", "a") or die ('Unable to open log file');
      fwrite($myfile, "[" . date("d/m/Y H:i:s") . "] " . $string . "\n");
      fclose($myfile);
    }

即使 $body = $res->getBody();应该返回一个流,它会用交换数据迅速填满磁盘,这意味着它试图在流回客户端之前将其保存在内存中,但这不是预期的行为。我错过了什么?

最佳答案

您必须指定 stream sink 像这样的选项:

$res = $client->request('GET', 'http://localhost:3002/', [
    'stream' => true,
    'sink' => STDOUT, // Default output stream.
    'on_headers' => ...
]);

在这些添加之后,您将能够逐块流式传输响应,而无需任何额外的代码从响应正文流复制到 STDOUT(使用 echo)。

但通常您不想这样做,因为您需要为每个事件客户端拥有一个 PHP 进程(php-fpm 或 Apache 的 mod_php)。

如果您只想提供 secret 文件,请尝试使用“内部重定向”:通过 X-Accel-Redirect 头用于 nginx 或 X-Sendfile 用于 Apache。您将获得相同的行为,但资源使用较少(因为在 nginx 的情况下具有高度优化的事件循环)。有关配置详细信息,您可以阅读官方文档,当然也可以阅读其他 SO 问题(例如 this one )。

关于php - 使用 PHP 和 Guzzle 流式传输远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38702570/

相关文章:

javascript - 从同一页面获取特定类字段内容(Javascript 或 PHP)

php - Symfony2 + Doctrine 关联错误 : Class Game has no association named home

python - 从服务器流式传输大量屏幕截图

Laravel 在 Laravel 之前捕获错误

php - Guzzle HTTP 请求从 POST 转换为 GET

php - HTML 表格到图像

PHP 与 MySQL Workbench : Same query, 不同的结果

c# - 如何在开始写入 ASP.NET Core 中的 HttpContext.Response.Body 流后更改 http 状态代码?

c# - 在 iOS 上录制实时音频流

php - 循环 PHP 嵌套数组 - 将值提取到 Blade Views (Laravel)