Example of forcibly downloading a PDF file using PHP

Source: Internet
Author: User
When you need to download a PDF file, if it is not processed, it will open the PDF file directly in the browser, and then you need to save it as a file to save the download, below we can use PHP to directly download PDF files. sometimes we encounter such a situation. when we need to download a PDF file, if it is not processed, it will open the PDF file directly in the browser, then you need to save the downloaded file by saving it as a file. 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:
The 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.