允许脚本读取文件,但阻止用户直接查看文件 [英] Allow scripts to read a file but prevent users from viewing the file directly
问题描述
假设我有一个纯文本文件example.txt
,并且我的Web服务器readfile.php
上有一个PHP脚本.
Lets say I have a plain text file example.txt
and I have a PHP script on my web-server readfile.php
.
我想做的是防止用户键入http://www.example.com/example.txt
并直接查看文本文件,但我仍然希望人们能够加载http://www.example.com/readfile.php
,该文件将从文件example.txt
中读取并执行带有某些内容(可能会显示文件的内容).
What I want to be able to do is to prevent users from typing http://www.example.com/example.txt
and looking at the text file directly but I still want people to be able to load http://www.example.com/readfile.php
which reads from the file example.txt
and does something with it (possibly displays the contents of the file).
此外,如果可以做到,那么最好的方法是什么?
Also, if this can be done, what is the best way to do it?
推荐答案
是的,这很容易做到.
有两种主要方法可以阻止用户访问example.txt
.第一种是将其放置在Web文件夹之外的文件夹中(通常称为www
或public_html
),第二种是使用您的example.txt脚本将.htaccess
文件放入文件夹中,该脚本会阻止对该文件的访问共. .htaccess
看起来像
There are two main ways to stop users from accessing example.txt
. The first is to put it in a folder outside your web folder (Usually called www
or public_html
), the second is to put a .htaccess
file in the folder with your example.txt script which blocks access to the file altogether. The .htaccess
would look like
<files "example.txt">
deny from all
</files>
但是,如果要阻止文件夹中的所有.txt
文件,可以将example.txt
更改为*.txt
.
But you could change example.txt
to something like *.txt
if you wanted to block all .txt
files in the folder.
然后,您可以在 file_get_contents()
中使用您的readfile.php
来获取文本文件的内容,或者如果您只想输出该文件,则可以使用 readfile
Then you can use file_get_contents()
in your readfile.php
to get the contents of the text file, or if you just want to output the file you can use readfile
这篇关于允许脚本读取文件,但阻止用户直接查看文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!