简体   繁体   中英

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.

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?

add this in .htaccess file in parent folder:

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:

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). 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.

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.

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

Then in 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"; 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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