使用 PHP 提供大文件 [英] Serving large files with PHP

查看:21
本文介绍了使用 PHP 提供大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图通过 PHP 脚本提供大文件,它们不在网络可访问目录中,所以这是我能想到的最好的方法来提供对它们的访问.

So I am trying to serve large files via a PHP script, they are not in a web accessible directory, so this is the best way I can figure to provide access to them.

我能想到的立即提供此文件的唯一方法是将其加载到内存中(fopen、fread 等),将标头数据设置为正确的 MIME 类型,然后只回显文件.

The only way I could think of off the bat to serve this file is by loading it into memory (fopen, fread, ect.), setting the header data to the proper MIME type, and then just echoing the entire contents of the file.

这样做的问题是,我必须一次将这些约 700MB 的文件加载到内存中,并将整个文件保存在那里,直到下载完成.如果我可以在下载时流式传输我需要的部分,那就太好了.

The problem with this is, I have to load these ~700MB files into memory all at once, and keep the entire thing there till the download is finished. It would be nice if I could stream in the parts that I need as they are downloading.

有什么想法吗?

推荐答案

您不需要阅读整个内容 - 只需进入一个循环,以 32Kb 的块读取它并将其作为输出发送.更好的是,使用 fpassthru ,它对你做同样的事情......

You don't need to read the whole thing - just enter a loop reading it in, say, 32Kb chunks and sending it as output. Better yet, use fpassthru which does much the same thing for you....

$name = 'mybigfile.zip';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: application/zip");
header("Content-Length: " . filesize($name));

// dump the file and stop the script
fpassthru($fp);
exit;

甚至更少的行,如果你使用 readfile,它不需要 fopen打电话...

even less lines if you use readfile, which doesn't need the fopen call...

$name = 'mybigfile.zip';

// send the right headers
header("Content-Type: application/zip");
header("Content-Length: " . filesize($name));

// dump the file and stop the script
readfile($name);
exit;

如果你想变得更可爱,你可以支持Content-Range 标头允许客户端请求文件的特定字节范围.这对于向 Adob​​e Acrobat 提供 PDF 文件特别有用,它只请求呈现当前页面所需的文件块.这有点复杂,但请参阅此示例.

If you want to get even cuter, you can support the Content-Range header which lets clients request a particular byte range of your file. This is particularly useful for serving PDF files to Adobe Acrobat, which just requests the chunks of the file it needs to render the current page. It's a bit involved, but see this for an example.

这篇关于使用 PHP 提供大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆