Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block direct access to a file over http but allow php script access

I'm loading my files (pdf, doc, flv, etc) into a buffer and serving them to my users with a script. I need my script to be able to access the file but not allow direct access to it. Whats the best way to achieve this? Should I be doing something with my permissions or locking out the directory with .htaccess?

like image 844
Brandon G Avatar asked Apr 21 '10 00:04

Brandon G


People also ask

How do I protect PHP files from direct access?

The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.


2 Answers

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow Deny from all 

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

like image 78
Sam Bisbee Avatar answered Oct 17 '22 22:10

Sam Bisbee


That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">   Order allow,deny   Deny from all </Files> 

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

like image 42
Aamir Mahmood Avatar answered Oct 17 '22 21:10

Aamir Mahmood