如何允许用户下载存储在 webroot 之外的文件?

How can I allow a user to download a file which is stored outside of the webroot?(如何允许用户下载存储在 webroot 之外的文件?)
本文介绍了如何允许用户下载存储在 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. 完成

您也可以使用 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 之外的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)