Use PHP to force the download of the PDF file example
- 2020-12-19 20:56:28
- OfStack
We sometimes have the situation that when we need to download an PDF file, if it is not processed, the PDF file will be opened directly in the browser, and then we need to save the downloaded file by saving as. This article uses PHP to download PDF files directly.
How it works: All we need to do is change the page HTTP header and set Content-ES8en to ES9en-ES10en to solve the problem.
See the code:
For convenience, I wrote a function, forceDownload(), and then called it.
How it works: All we need to do is change the page HTTP header and set Content-ES8en to ES9en-ES10en to solve the problem.
See the code:
forceDownload("pdfdemo.pdf");
function forceDownload($filename) {
if (false == file_exists($filename)) {
return false;
}
// http headers
header('Content-Type: application-x/force-download');
header('Content-Disposition: attachment; filename="' . basename($filename) .'"');
header('Content-length: ' . filesize($filename));
// for IE6
if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
header('Cache-Control: no-cache, must-revalidate');
}
header('Pragma: no-cache');
// read file content and output
return readfile($filename);;
}
For convenience, I wrote a function, forceDownload(), and then called it.