I have been looking to find a good guide on how to securely download files from a website only if a user session exists.
The files in the download folder should NOT be accessible if a user session doesn’t exist.
Therefore I assume the folder the files are stored in needs to be “locked” by a .htaccess file? Alternatively stored outside the root folder? Which is the best?
If anyone could point me to a good guide/tutorial for this it would be very much appreciated. Thanks
Advertisement
Answer
This is what I ended up doing which worked well. In my scenario I store my files outside of the root folder.
JavaScript
x
$filename= $_GET['filename'];
// the file path and file you want to send inline
$path = $fileroot."/files/".$filename;
if(!file_exists($path)) {
die("There has been an error unfortunately");
}
// the file name of the download, change this if needed
$public_name = basename($path);
// get the file's mime type to send the correct content type header
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $path);
// header("Content-Disposition: attachment; filename=$public_name;");
//Use "attachment" instead of inline if you want direct download instead
// send the headers
header("Content-Disposition: inline; filename=$public_name;");
header("Content-Type: $mime_type");
header('Content-Length: ' . filesize($path));
readfile($path);