Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

php

Lets say I have a plain text file example.txt and I have a PHP script on my web-server readfile.php.

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?

like image 400
mmtauqir Avatar asked Aug 08 '11 05:08

mmtauqir


1 Answers

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 
</files>

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

like image 147
Paul Avatar answered Sep 27 '22 16:09

Paul