force download - authenticated download

PHP Add comments

Basically downloads are normal direct link to real files in the server with a complete static url link to the file. So any body can click the link and can download the file. Any cross site script can access the file any time or any user can access the file from anywhere.

What if you want to allow file downloads only if the user is logged in.
what if you want to hide the actual file and its folder from displaying it to the user instead you want to show a different url which could probably be a server side script file (.php for example). and that could fetch the actual file with a different name.

For that i use the force download concept. I will just send the id of a file for which its filename and location are always hidden. take this for example…

<a href=''>Click here to download</a>

and in files.php firstly i will check whether the users has logged in and only then i will let the file to download… else nothing happens.

here is a sample code to do a force download.

//select fn from tablename where id=$_request[id]
//assume that the file is in the junk named folder
// the the force download script will look like the following
$filename = "doc_O1jtIYi4jkg8Xh2k/$fn";
header("Cache-Control: no-store");
header("Expires: 0");
header("Content-Type: application/octet-stream");
header("Content-disposition: attachment; filename=\"".basename($filename)."\"");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));

the readfile function reads the contents of a file and outputs to the client.
cache control no-store if for geko browsers and no-cache can be included for IE browsers
You can either use the exact mime type if you know in the place of content-type.

This works in all browsers. People either download, save and view the file or they directly open the file. When they do the second and if their browser is IE 6 then you get a message that ‘cannot access file from temporary internet folder’ so for IE 6 the users has to save the file first and then they have to open it.

If you find any sense if not appropriate then please post a comment.

Leave a Reply

Entries RSS