繁体   English   中英

防止直接访问html文件,但允许通过PHP?

[英]Prevent direct access to html file but allow through PHP?

我有一个我希望保护的网站部分。 我创建了一个PHP脚本来验证密码,一旦验证,我希望它们被定向到一个HTML页面。

www.mywebsite.com/protectedfolder/index.html

我不希望用户使用上述网址,将其粘贴到浏览器中,然后访问该网页。 我必须添加我的.htaccess文件吗?

将其添加到父文件夹中的.htaccess文件中:

RewriteEngine On

RewriteBase /
RewriteRule ^protectedfolder/index\.html$ / [NC,R,L]
# OR THIS TO PROTECT ALL FOLDER
# RewriteRule ^protectedfolder / [NC,R,L]

或者在受保护的文件夹中创建.htaccess文件并写下:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

当php脚本运行时,它从当前用户访问文件(而不是通过http)。 因此,当尝试使用php的file_get_contents(),readfile(),fopen()等从受保护的文件夹中读取文件时,apache的规则不会阻止php使用文件系统进行IO操作。

如果我们想要将受保护文件夹中的输出文件发送给经过身份验证的用户,我们必须运行以

if(hasAccess()) {
    print readfile('path/to/protectedfolder/file.html');
}

我会使用PHP和一个带密码输入的表单来提供服务器的POST请求。

<form action="index2.php" method="POST">
    <input name="pass" type="password" />
</form>

然后在PHP中

if (empty($_POST["pass"]) || $_POST["pass"] != "yourpasshere") {
    header("Location index1.html");
    die();
}
//your second page here

编辑:您也可以使用会话进行此操作,用户在某个位置登录,您为他们提供一个会话名称,如$_SESSION["name"] = "admin"; 然后以类似于上面的方式检查它

session_start();
if (empty($_SESSION["name"])) {
    header("Location index1.html");
    die();
}
//your second page here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM