简体   繁体   English

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

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

I have a section of my website I would like to protect. 我有一个我希望保护的网站部分。 I have created a php script to authenticate passwords and once authenticated, I would like them to be directed to an html page. 我创建了一个PHP脚本来验证密码,一旦验证,我希望它们被定向到一个HTML页面。

www.mywebsite.com/protectedfolder/index.html

I don't want users to take the above url, paste it into their browsers and have access to the page however. 我不希望用户使用上述网址,将其粘贴到浏览器中,然后访问该网页。 Do I have to add something my .htaccess file? 我必须添加我的.htaccess文件吗?

add this in .htaccess file in parent folder: 将其添加到父文件夹中的.htaccess文件中:

RewriteEngine On

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

or create .htaccess file in protected folder and write this: 或者在受保护的文件夹中创建.htaccess文件并写下:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

when php script runs and it accesses files it does from current user (not through http). 当php脚本运行时,它从当前用户访问文件(而不是通过http)。 so when trying to read file from protected folder using php's file_get_contents(), readfile(), fopen() and etc. apache's rules does not prevent php to make IO operations with file system. 因此,当尝试使用php的file_get_contents(),readfile(),fopen()等从受保护的文件夹中读取文件时,apache的规则不会阻止php使用文件系统进行IO操作。

and if we want output files from protected folder to authenticated users we have to run something like: 如果我们想要将受保护文件夹中的输出文件发送给经过身份验证的用户,我们必须运行以

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

I would use PHP and a form with password input that would provide a POST request to the server. 我会使用PHP和一个带密码输入的表单来提供服务器的POST请求。

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

Then in PHP 然后在PHP中

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

EDIT: You could also do this with sessions, where a user logins at a certain location, you give them a session name like $_SESSION["name"] = "admin"; 编辑:您也可以使用会话进行此操作,用户在某个位置登录,您为他们提供一个会话名称,如$_SESSION["name"] = "admin"; and then check for that in a way similar to above with 然后以类似于上面的方式检查它

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