Reputation: 427
how can I download a file from directory which is "protected" against direct access via .htaccess?
So the file is in /var/www/web1/domain.com/protecteddirectory/file.png
and I want to use a PHP-script which checks if user is allowed to download (already done) and initiates download after that.
This is my source so far:
public function downloadAttachment()
{
$id = JRequest::getInt('id');
$user = JFactory::getUser();
$model = $this->getModel('Attachment');
$item = $model->getAttachment($id);
if(!$user->guest)
{
echo "<p><strong>Check if you are allowed to download...</strong></p>";
if($user->get('isRoot'))
{
echo "<p><strong>Preparing...</strong></p>";
$filename = $item->filename; //Name to display
$filepath = $item->filepath;
// start download now...
}
}
else
{
echo "<p><strong>You are not allowed to download this file...</strong></p>";
}
}
How can I solve this? In best case the filetype is detected automatically because it's possible to download png, zip, txt, doc, pdf and so on.
Upvotes: 2
Views: 1292
Reputation: 427
I was able to solve this using this code:
$size = filesize($file);
header ( 'Content-Description: File Transfer' );
header("Content-Type: application/force-download");
header ( 'Content-Type: application/octet-stream' );
header ( 'Content-Disposition: attachment; filename=' . basename ( $file ) );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
ob_clean();
flush();
readfile ( $file );
exit();
Upvotes: 1