Download files through authentication
I recently needed to implement a way for authenticated users to download files. Normally to host a file for download on a site you would need to provide the url to the download. www.yourdomain.com/restrictedfile.pdf.
You could then authenticate the user and only provide the link if the user was authenticated; however, there is nothing preventing users from simply typing the url into the browser and downloading the sensitive information.
This is why i created a script with php to fetch the file only when the user session is active. The restricted files are on the webserver but stored in an a directory that Apache has no access to.
$file = $_GET['file'];
$download_folder = '../RestrictedFiles';
$file = basename($file);
$filepath = "$download_folder/$file";
if (file_exists($filepath)) {
//.... check to see if user is logged in ...
// connect to database
// include auth and nav
// close mysql connection
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file");
session_write_close();
readfile($filepath);
} else {
echo 'The file you are trying to download is not found. If you think this is an error
please contact us.';
}
To see an example in ASP see: ASP Example







[...] wrote my first article on July 6th [...]
Hello, I am very new at this and honestly need to know exactly how to do this. Do you know a step by step process. I do not want to upload into my website until I have tested it on my local machine
Scenario, I have an HTML file that I open within a folder, however I want to simply require a password before can view it. Nothing really critical, just want to keep the masses out.
If I put the .htaccess file in that directly, and the .htpasswd in the same directory, how will that keep me from accessing the html file. when that is what I need to click on to test. am I missing something here? Does the index.html on the server automatically look for this password file?
Anything would be great. or maybe you could direct me to a fully laid out example
Thank you for your time
Paul
.htaccess is basically a config file that tells apache what to do. You can add things in there like authentication. Which would require username/password combo (supplied in .htpasswd).
Check this link out for more info.