php - 如果通过身份验证,则允许下载文件

标签 php .htaccess

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

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

使用 handle.php 文件验证用户并查看他们是否有高级帐户。

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

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

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

最佳答案

你的重写规则很好......除了你应该添加一个条件来检查并确保 REQUEST 不是“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 中,您可以检查该变量是否存在——如果存在,则允许下载。否则将用户重定向到登录。

关于php - 如果通过身份验证,则允许下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370438/

相关文章:

php - HTML/PHP/MYSQL - 如何使用 MYSQL 中的 2 个不同字段填充下拉列表

php - 删除整数索引数组

php - htaccess 将所有重定向到 https 到 http 除了一个文件夹

linux - Apache RewriteEngine On 导致 403 错误

.htaccess - htaccess 重定向 if 条件汉字

php - HTACCESS : Dynamic rewrite url with multiple variables

PHP base64_解码! "@"作为 "¡"出来

PHP 只获取目录路径

apache - 如何使用 mod_headers 和 mod_expires 进行缓存

php - 带有 .htaccess 的漂亮 URL