要么覆盖 htaccess 的行为,要么覆盖从 URL 访问文件的不同解决方案


Either override behaviour of htaccess or a different solution for file access from URL

它做什么?

  1. 对 PDF 文件的所有请求都将重定向到验证.phphtaccess
  2. 验证.php 获取日志。
  3. 验证.php验证用户是否登录。
  4. 如果未登录,则将用户踢出。如果已登录,则显示 PDF文件。

问题:显然,由于htaccess的行为,第四步(如果登录则显示PDF文件)失败。

问:如何解决此问题?

谢谢

HTACCESS:

RewriteEngine On
RewriteCond %{REQUEST_URI} '.(pdf)$ [NC]
RewriteRule ^(.*)$ /validate.php?filename=$1 [L]

验证.php:

//STEP 1) Take a log
$file = 'log.txt';
$current = file_get_contents($file);
$current .= (isset($_GET['filename'])) ? $_GET['filename'] : '?';
$current .= " --- " . date('H:i:s') . "'n";
file_put_contents($file, $current);

//STEP 2) Authenticate login
session_start();
if (! isset($_SESSION['user']))
{
    session_write_close();
    header ('Location: /login.php');
    exit();
}
else
{
    //User should be eble to see the PDF file now.
}

//User should be eble to see the PDF file now.步骤中,只需输出文件,而不是将用户重定向到 pdf 文件。所以像这样:

$file = $_GET['filename'];
$filename = basename($file);
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);