Reputation: 711
I have been trying to force download PDF files in browser, I have succeeded in this and files are being downloaded. But when I open the downloaded PDFs they are not showing up properly, something like decoded or can't see the fonts and images properly instead of showing some weird texts and icons. Here is the code I am using to download the file:
//Here I am getting the complete path to pdf file
$file_url = stripslashes( trim( $theFile ) );
//get filename
$file_name = basename( $theFile );
//get fileextension
$file_extension = pathinfo($file_name);
//security check
$fileName = strtolower($file_url);
//var_dump($file_url, $file_name, $file_extension); die();
//var_dump($file_name); die();
$file_new_name = $file_name;
header("Expires: 0");
header("Cache-Control: no-cache, no-store, must-revalidate");
header('Cache-Control: pre-check=0, post-check=0, max-age=0', false);
header("Pragma: no-cache");
header("Content-type: application/pdf");
header("Content-Disposition:attachment; filename={$file_new_name}");
header("Content-Type: application/force-download");
readfile("{$file_url}");
exit();
Is there anything extra I want to add in this code to fix the issue?
Upvotes: 0
Views: 2513
Reputation: 605
Follow PHP document,
Note:
readfile() will not present any memory issues, even when sending large files, on its own.
If you encounter an out of memory error ensure that output buffering is off with ob_get_level().
And this link PHP readfile() causing corrupt file downloads, removing all spaces before the opening PHP tag (<?php
) on the first line.
In short, spaces will corrupt your binary file.
<?php
...
// clean all levels of output buffer
while (ob_get_level()) {
ob_end_clean();
}
readfile("{$file_url}");
exit();
Upvotes: 1