We sometimes encounter this situation. When we need to download a PDF file, if it is not processed, we will open the PDF file directly in the browser, and then save it as a file to save the download. This article uses PHP to directly Download PDF files.
Implementation principle: we only need to modify the HTTP header of the page and set Content-Type to force-download to solve the problem.
See the Code:
Copy codeThe Code is as follows:
ForceDownload ("includemodownload ");
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.