服务与PHP大文件 [英] Serving large files with PHP

查看:118
本文介绍了服务与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;

如果你想获得可爱,甚至,你可以支持内容范围头,它可以让客户端请求的文件的特定字节范围。这是PDF文件提供到Adobe Acrobat,这只是要求它需要使当前页的文件块特别有用。这是一个有点麻烦,但看到这样的例子

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天全站免登陆