PHP 保护目录不被直接 URL 访问

2024-01-08

我有一个管理员脚本。

admin/index.php

所有的活动都是通过这个完成的index.php file.
用户在获得程序功能的访问权限之前先登录。
$_SESSION['user_authenticated']创建并设置为true.

admin/template/..

该文件夹包含images, css, javascript files.
它们仅在此 ADMIN 内使用。 (仅在后端)

问题:

我需要来自的所有内容admin/template/..受保护的目录直接访问.
它应该只对经过身份验证的用户可用。

我想一定有一个.htaccess将请求重定向到check_session_auth_variable.php,看起来如果$_SESSION['user_authenticated'] is true or false and 重定向到请求的文件 or 抛出 404 错误?

我知道最好的选择是将目录放置在 Web 根目录之外,但就我而言,我需要保持目录结构不变,无需修改。


管理/.htaccess:

RewriteCond %{REQUEST_FILENAME} !check_auth.php
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* check_auth.php?file=$0 [QSA,L] # pass everything thru php

管理/check_auth.php:

$file = $_GET['file'];
if($_SESSION['user_authenticated']) {
    // please mind you need to add extra security checks here (see comments below)
    readfile($file); // if it's php include it. you may need to extend this code
}else{
   // bad auth error
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP 保护目录不被直接 URL 访问 的相关文章