Is there anyway to control file access with PHP? For example, would it be possible to restrict users from downloading a file from my website unless they're logged in? I'm sure this would have to do with some sort of file system rights on the server end. Would this incorporate .htaccess? I've been wondering if this were possible for quite some time. I've written a script that tracks both streaming and downloading of media files on my website. It isn't solid though. Someone could easily navigate to where the file is on my website and stream/download it without having to get it through my script.
I'm sure there will be a way, but I'm not so sure what that would be. Most people simply cloak the URL to the file and then use PHP to load it in using the header function. I've put you together a script that shows you how to achieve that.
Fundamentally, what it does is checks the file they're after, strips the forward slashes to prevent against relative directory trawling, checks to see it if exists, if it does then it will prompt the user to download the file.
I have even added a little mod-rewrite which allows the URL to look like so: /file/my_file.zip.
Someone could easily navigate to where the file is on my website and stream/download it without having to get it through my script.
Keep the files in a non-web-accessible folder; either use .htaccess to block requests or throw the files into a folder below the web root.
Folder below web root
If the main folder for your site is /home/salathe/public_html/ then store the files outside of that folder; e.g., /home/salathe/file_store/ This way, it's simply not possible to type an URL which equates to the location of that folder!
Block access with .htaccess file
There are various ways you could achieve this but here's just one of them. Put a .htaccess file in the folder storing the files (e.g. /home/salathe/public_html/files/), with the following content.
Deny from all
Since you're using PHP to output the files (with authorisation checking, etc.) then it doesn't matter where the files are stored in the server so long as PHP can read them. :)
The Following User Says Thank You to Salathe For This Useful Post: