View Full Version : How to do a protected file download

03-22-2011, 02:34 PM

I've got a login system for my site and it all works fine and dandy for protecting pages.

However what I would like to do is allow people who are logged in to download a file and prevent people direct linking to the file.

I don't know if I have to use htaccess for this or php or combination of both... How would I do this?


03-22-2011, 02:50 PM
There are several ways to do this and the there was a debate about it a while back on this or sitepoints forum as to whether or not it actually works.

I personally think that this method does work as long as you take the correct steps to protect the file download.

Firstly you need to be on a server which lets you use set_time_limit() because you really need your php script to be outputting the file stream in a loop.

Second you need to store the files outside of your public_html so that people cannot directly access them any other way other than use your script. That way your script is the only way to access the files.

Thirdly you need to make use of register_shutdown_function() to determine if the file download was finished or not. If not you keep your download details active in the database. If it was completed then you just adjust those details so that the script knows not to offer it for download again.

It's not really an easy one to show you in code but if you look at ways of doing what I've said above and break it down you should be able to come up with your own code.