上传根目录以外的文件(Upload files outside of webroot)

2019-08-06 20:38发布

我正在开发一个购物系统,其中shopmanager应该能够将文件上传到系统中。 这些文件可以卖到上费,只应通过提供对购买代码入店。

整个申购代码和上传的事情是工作的罚款。 只要有阻止该文件的直接访问。

问题:

  • 我怎样才能让用户根目录以外的上传而不是从那里读/下载?
  • 或者我如何允许用户从上传到一个目录,但没有人能读/下载?

我运行Apache和使用这样的代码通过表格来上传文件:

 public function upload_file($file='',$post_value='',$path) {
  if ($_FILES[$post_value]) {
      $uploadext = strtolower(strrchr($_FILES[$post_value]['name'],"."));
      if($uploadext=='.jpg' || $uploadext=='.gif' || $uploadext=='.png' || $uploadext=='.swf' || $uploadext=='.jpeg' || $uploadext=='.pdf' || $uploadext=='.doc' || $uploadext=='.xls' || $uploadext=='.docx') {
    $destination = $path.$file.$uploadext;
       move_uploaded_file($_FILES[$post_value]['tmp_name'], $destination);
   } else {
    echo PICTURE_ERROR;
   }
  }
  return $file.$uploadext;
 }

Answer 1:

你可以上传任何你想使用move_uploaded_file函数,只要确保Web服务器可以在目标目录写。

当你需要创建一个脚本,将读取该文件,并把它传递给浏览器,这样你可以确保用户已经支付了文件。

例子

<?php
// insert your logic here to verify the user has access to this file.
// open the file in a binary mode
$name = 'yourfile';

$fp = fopen($name, 'rb');

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

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

?>

你必须要小心的内容类型也确保用户无法您的服务器的每一个文件,如果您使用$ _GET变量用于获取文件名。



Answer 2:

这实际上是很容易的。 只要创建你的文件的目录,并给予apache的权限来写它。 然后当你调用move_uploaded_file()功能你可以指定目标到该目录。 PHP运行服务器端,因此将能够访问该目录,在使用浏览器的用户将仅限于什么Apache将允许他们访问。

如果你需要下载这些文件,只需创建一个脚本,将解析URL参数(或东西),并采取从文件目录中的文件,并将它推到浏览器。



Answer 3:

使用.htaccess文件或配置的apache.conf不允许到上传目录的直接访问。

<Directory /path/to/upload/dir>
   Order Deny,Allow
   Deny from All
</Directory>


Answer 4:

这很可能是最简单的,在确保文件的条款,将文件保存你的根目录之外。 当有人想下载的话,你可以使用http_send_file将文件发送回给他们。



文章来源: Upload files outside of webroot