4

我在 .htaccess 文件中有一个 RewriteRule:

RewriteRule ^folder/(.*)$ folder/handle.php?path=$1 [L]

使用文件对用户进行身份验证,handle.php并查看他们是否拥有高级帐户。

我想[1]检查用户是否未通过身份验证,然后页面显示错误,otherwise [2]下载开始 & 我不想使用任何 PHP 类或脚本来处理文件下载(只是没有 php 的普通服务器端下载处理)。

我怎样才能做到这一点?可能吗?

请求文件下载的 URL:http://mywebsite.com/folder/file.zip

4

1 回答 1

0

你那里的重写规则很好......除了你应该添加一个条件来检查并确保请求不是“handle.php” - 否则你可能会得到一个重定向循环。

现在,在您的 handle.php 文件中 - 这是处理该文件夹中的所有文件请求。

在handle.php 中,您可以使用$_GET['path']来获取请求的文件名。在 handle.php 中,您可以包含您的身份验证检查。如果身份验证检查通过,您可以继续对readfile用户进行操作。handle.php 的一个例子:

<?php
set_time_limit(0);
session_start();
include "../some_functions_auth_file.php";

// NOTE: better file checking should be implemented here. We're using basename() for now.
$file = !empty($_GET['path']) ? basename($_GET['path']) : false;
if($file === false || !file_exists($file)) die("Invalid file.");

if(user_is_authenticated()) {
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
  header("Cache-Control: no-store, no-cache, must-revalidate"); 
  header("Cache-Control: post-check=0, pre-check=0", false ); 
  header("Pragma: no-cache" ); 
  header("Content-Type: application/octet-stream");
  header("Content-Length: " .(string)(filesize($file)) );
  header('Content-Disposition: attachment; filename="'.$file.'"');
  header("Content-Transfer-Encoding: binary\n");
  readfile($file);
  exit;
} else {
  header("Location: ../login.php");
}
?>

请注意,这是非常基本且未经测试的

现在,如果您不想使用readfile(因为它很慢),那么也许您可以设置一个 Apache 环境变量...然后,在 .htaccess 中,您可以检查该变量是否存在 - 如果存在,允许下载。否则将用户重定向到登录。

于 2013-06-28T17:45:44.233 回答