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

问题描述:

我有一部分要保护.我已经创建了一个PHP脚本来对密码进行身份验证,并且一旦身份验证完毕,我希望将它们定向到html页面.

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

我不希望用户使用上述url,将其粘贴到他们的浏览器中,但是可以访问该页面.我必须添加.htaccess文件吗?

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:

RewriteEngine On

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

或在受保护的文件夹中创建.htaccess文件,并编写以下内容:

or create .htaccess file in protected folder and write this:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

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

如果我们希望将文件从受保护的文件夹输出到经过身份验证的用户,则必须运行以下命令:

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');
}