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

使用PHP流式传输大型文件

我有一个200MB的文件,我想通过下载给用户。但是,由于我们希望用户只下载一次该文件,我们这样做:

echo file_get_contents('http://some.secret.location.com/secretfolder/the_file.tar.gz');

强制下载。但是,这意味着必须将整个文件加载到内存中,这通常不起作用。我们怎样才能将这个文件传输给它们,每块大约kb?


小唯快跑啊
浏览 448回答 3
3回答

Cats萌萌

使用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 headersheader("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标头。
打开App,查看更多内容
随时随地看视频慕课网APP