上传webroot之外的文件

时间:2009-09-16 13:50:26

标签: php forms file-upload

我正在开发一个购物系统,shopmanager应该能够将文件上传到系统。这些文件可以收费出售,只能通过提供购买代码才能获得。

整个购买代码和上传工作正常。只需要阻止直接访问该文件。

问题:

  • 如何允许用户在webroot之外上传但不能从那里上传/下载?
  • 或者我如何允许用户上传到目录但没有人可以从中读取/下载?

我正在运行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;
 }

4 个答案:

答案 0 :(得分:4)

您可以使用move_uploaded_file函数上传任何地方,只需确保网络服务器可以在目标目录中写入。

必须创建一个可以读取文件并将其传递给浏览器的脚本,这样您就可以确保用户已经支付了该文件。

为例

<?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变量来获取文件名,则必须注意内容类型,同时确保用户不能使用服务器的每个文件。

答案 1 :(得分:0)

这实际上非常简单。只需为您的文件创建一个目录,并授予apache权限以写入它。然后,当您调用move_uploaded_file()函数时,您只需指定该目录的目标。 PHP运行服务器端,因此它可以访问该目录,而使用浏览器的用户将仅限于Apache允许他们访问的内容。

如果您需要下载这些文件,只需创建一个解析URL参数(或其他内容)的脚本,然后从files目录中取出该文件并将其推送到浏览器。

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

在保护文件方面,将文件保存在webroot之外可能是最简单的。当有人想下载它时,您可以使用http_send_file将文件发回给他们。

相关问题