如何允许用户下载存储在webroot之外的文件? [英] How can I allow a user to download a file which is stored outside of the webroot?

查看:204
本文介绍了如何允许用户下载存储在webroot之外的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个允许注册用户(谁可以是任何人)上传文件的系统。我已经阻止mime类型等尝试将文件限制为.doc,.docx和.pdf类型,但为了额外的安全性,它们被上传到webroot之外的文件夹。

I am developing a system which allows registered users (who could be anybody) to upload files. I've block mime-types etc. to attempt to restrict the files to .doc, .docx and .pdf types, but for additional security, they are uploaded to a folder outside the webroot.

其他用户可以选择下载文件。我如何让他们这样做?显然,我不能仅仅放置一个链接到文件,因为它是在webroot之外。我不知道如何达到文件!我假设我可以使用php文件功能来获取文件,但是如何才能对已经请求的用户提供服务?

Other users can then choose to download the files. How do I allow them to do that? Obviously I can't just put in a link to the file, as it's outside the webroot. I'm not sure how to reach the file though! I presume I can use the php file functions to get to the file, but how do I then 'serve it up' to the user who has requested it?

什么安全可能所有这些都有可能吗?

What security implications might all of this have?

谢谢。

推荐答案

你需要一个PHP脚本,执行以下操作:

You need a PHP script that does the following:


  1. 正确设置内容类型标题(取决于用户正在下载的内容)

  2. 正确设置内容长度标题(取决于文件大小)

  3. 打开文件进行阅读(可以使用fopen)

  4. 读取文件并将其内容输出到输出流

  5. 完成

  1. Set the content-type header correctly (depending on what the user is downloading)
  2. Set the content-length header correctly (depending on the file size)
  3. Open the file for reading (you can use fopen)
  4. Read the file and output its content to the output stream
  5. Done

您还可以使用 readfile 功能做基本相同的操作。以下是PHP网站的一个例子:

You can also use readfile function to do basically the same. Here's an example from PHP's site:

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

这篇关于如何允许用户下载存储在webroot之外的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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