PHP force file Download instead of the custom function opened in the browser share _php instance

Source: Internet
Author: User
Sometimes we want pieces, text documents, Web pages, MP3, PDFs, and so on, when clicked on the corresponding link to download directly, rather than on the page display, then you need to force the header header information. The following is a piece of PHP function implementation code that does not produce garbled, other programming languages can also be referenced to write the implementation.
Copy CodeThe code is as follows:
/**
* Downloader
*
* @param $archivo
* Path Al Archivo
* @param $downloadfilename
* (null|string) el nombre que queres usar para el archivo que se va a descargar.
* (Si no lo especificas usa el nombre actual del archivo)
*
* @return File stream
*/
function Download_file ($archivo, $downloadfilename = null) {

if (file_exists ($archivo)) {
$downloadfilename = $downloadfilename!== null? $downloadfilename: basename ($archivo);
Header (' Content-description:file Transfer ');
Header (' Content-type:application/octet-stream ');
Header (' content-disposition:attachment; Filename= '. $downloadfilename);
Header (' content-transfer-encoding:binary ');
Header (' expires:0 ');
Header (' Cache-control:must-revalidate, post-check=0, pre-check=0 ');
Header (' Pragma:public ');
Header (' Content-length: '. FileSize ($archivo));

Ob_clean ();
Flush ();
ReadFile ($archivo);
Exit
}

}

  • Related Article

    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.