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

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


Just store the files you don't want publicly accessible outside the webroot.

/home
   example.txt
   /www
      readfile.php

If /home/www/ is your public webroot folder, any file above it is not accessible through the web server. readfile.php can still access the file perfectly fine at ../example.txt though.


If you need to store the files in the webroot, then put the files in a folder and deny access to that folder. If you are using apache, make a .htaccess file in the folder and type in deny from all

Tags:

Linux

Php