Reputation: 1
i was trying to force download pdf files on my website. The file was downloaded successfully but an empty file is created in the same folder with a random name when download is clicked. i'm having multiple null files in the folder.
download.php :
<?php
$file = $_GET['file'];
header('Content-type: application/pdf');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="'.$file.'"');
?>
Upvotes: 0
Views: 338
Reputation: 26
Assuming you store your pdf in database.
//you need to decode
$decoded = base64_decode($downloaded->pdf);
//name of pdf
$filename =date('Ymdhis').'.pdf';
$size=strlen($decoded);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.($filename).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header('Content-Length:'.$size);
echo($decoded);
exit;
Please note, if you send some headers before it will not working.
Make sure you create properly your pdf file.
$decoded = base64_decode($downloaded->pdf);
$filename =date('Ymdhis').'.pdf';
//if file doesn't exists
if(!file_exists($filename)){
//we create file in the location
$fp=fopen($_SERVER['DOCUMENT_ROOT'].'/tmp/'.$dir_name.''.$filename,'a+');
//We write in
fwrite($fp, $decoded);
}
Upvotes: 1