PHP - 文件流问题
我有一个包含下载部分的网站。我需要匿名用户不能直接访问这些文件,因此我将它们放在用户无法访问但 Web 服务器可以访问的目录中。当用户单击链接下载文件时,我需要它重定向到下载页面,该页面会将文件流式传输给用户,而无需用户知道目录或文件的位置,并且会要求他将其保存到自己的计算机上。我在上一篇文章中找到了以下代码,但我无法让它正常工作。可能是我不知道它想要传递给它的变量的正确名称。请附上如何使用您的代码的说明。
$filename='Firefox%20Setup%203.6.13.exe';
$file_path='http://ftp.byfly.by/pub/mozilla.org/firefox/releases/3.6.13/win32/fr';
$file= $file_path."/".$filename;
$len=filesize($file);
header("content-type: application/save");
header("content-length: $len");
header("content-disposition: attachment; filename=$filename");
$fp=fopen($file, "r");
fpassthru($fp);
I have a website that has a downloads section. I need for the files not to be accessed directly by an annonymous user, so I am putting them in a directory not accessable to users, but is accessible to the web server. When the user clicks the link to download the file, I need it to redirect to a download page that will stream the file to the user without him knowing the location of the directory or the file and it will ask him to save it to his computer. I found the following code on a previous post, but I can't get it to work correctly. Could be that I don't know the correct names of the variables that it wants to be passed to it. Please include an explanation of how to use your code.
$filename='Firefox%20Setup%203.6.13.exe';
$file_path='http://ftp.byfly.by/pub/mozilla.org/firefox/releases/3.6.13/win32/fr';
$file= $file_path."/".$filename;
$len=filesize($file);
header("content-type: application/save");
header("content-length: $len");
header("content-disposition: attachment; filename=$filename");
$fp=fopen($file, "r");
fpassthru($fp);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我就是这样做的。
当然,最好先执行 HEAD 请求来获取文件大小并在响应中包含 Content-Length 标头,以便用户可以了解需要多长时间。或者,如果您始终要提供相同的文件,则可以对该数字进行硬编码。
This is how I would do it.
Of course, it would be better to do a HEAD request first to get the filesize and include a Content-Length header in the response so the user can have some idea about how long it is going to take. Or, you can hardcode that number, if you are always going to be serving up the same file.
假设您的目录中有一个名为“hiddenaccess”的文件,文件名为“test.mp3”,您可以在 php 变量中加载路径并让它进行下载
注意:此文件中没有任何其他 echo 或 print 语句。
Let's say you have a file in a directory called "hiddenaccess" and the file name is "test.mp3" you can load the path in php variable and let it for download
Note: Do NOT have any other echo or print statements in this file.
这是我(显然是其他人?!!?)开发的一个函数就是为了做到这一点,它是一个丰富的函数,但它检查并执行所有操作。虽然调用它很简单,但却是重要的部分。我在一个类中有这个函数,但你可以将它设为一个 php 函数,因为它没有依赖其他类函数。希望这对您有帮助。
使用它会是这样的。
Here's a function I (Apparently Others?!!?) developed to do just that, it's a meaty function but it checks and does everything. To call it is simple though, the important part. I have this inside a class but you can just make it a php function as there is no other class functions it depends on. Hope this helps you.
To use it would be something like this.