为了账号安全,请及时绑定邮箱和手机立即绑定

请问使用PHP流式传输大型文件

请问使用PHP流式传输大型文件

PHP
小唯快跑啊 2019-09-09 11:56:08
使用PHP流式传输大型文件我有一个200MB的文件,我想通过下载给用户。但是,由于我们希望用户只下载一次该文件,我们这样做:echo file_get_contents('http://some.secret.location.com/secretfolder/the_file.tar.gz');强制下载。但是,这意味着必须将整个文件加载到内存中,这通常不起作用。我们怎样才能将这个文件传输给它们,每块大约kb?
查看完整描述

3 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

使用fpassthru()。顾名思义,它不会在发送之前将整个文件读入内存,而是直接将其输出到客户端。

手册中的示例修改:

<?php


// the file you want to send

$path = "path/to/file";


// the file name of the download, change this if needed

$public_name = basename($path);


// get the file's mime type to send the correct content type header

$finfo = finfo_open(FILEINFO_MIME_TYPE);

$mime_type = finfo_file($finfo, $path);


// send the headers

header("Content-Disposition: attachment; filename=$public_name;");

header("Content-Type: $mime_type");

header('Content-Length: ' . filesize($path));


// stream the file

$fp = fopen($path, 'rb');

fpassthru($fp);

exit;

如果您希望将内容直接流式传输到浏览器而不是下载(如果浏览器支持内容类型,如视频,音频,PDF等),请删除Content-Disposition标头。



查看完整回答
反对 回复 2019-09-09
  • 3 回答
  • 0 关注
  • 446 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信