For example, if users want to download /webroot/files/bigimage.jpg, they are given a URL www.domain.com/download.php?filename=bigimage.jpg. Then,
EDIT: Make the question more clearer.
I am using LAMP stack. For Q1, I am not asking how to do authentication, I am asking how to prevent users access the file directly. Also, reading contents of the whole file and echo them is resource extensive. Is there better solution?
First step, drop a .htaccess file in the folder with the image that says "deny from all". This will prevent anyone from access the file even if they know the folder.
Then, you write use a PHP function like this
$file = 'path/to/folder' . $filename;
//Make sure you check that $filename does not contain ".." for security
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
} else {
//Show error message
}
You should be checking session variables to see if the user is logged and has a role that can download this. This code will also force download of the image than show it.
Set the header's content META tag to binary so browsers won't try to handle the file on their own.
header('Content-Type: application/binary');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With