mtahmed mtahmed - 4 years ago 74
Linux Question

Allow scripts to read a file but prevent users from viewing the file directly

Lets say I have a plain text file

and I have a PHP script on my web-server

What I want to be able to do is to prevent users from typing
and looking at the text file directly but I still want people to be able to load
which reads from the file
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?

Answer Source

Yes, this is easy to do.

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 

But you could change example.txt to something like *.txt if you wanted to block all .txt files in the folder.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download