PHP file stream download method

Source: Internet
Author: User
PHP method for downloading files using file streams 1. flush-Refresh Output Buffer 2. ob_clean-clear (erase) output buffer note: The above two functions can solve the DEMO of PHP file downloading garbled content: & lt ;? Phpfname is the name of the file to be downloaded. $ fpath is the folder where the downloaded file is located. the default value is downlodfunctiondownl... 1. flush-refresh the output buffer.
2. ob_clean-clear (erase) output buffer
Note: The above two functions can solve the problem of garbled characters in PHP download files.


DEMO:


// Fname is the name of the file to be downloaded
// $ Fpath indicates the folder where the downloaded file is located. the default value is downlevels.
Function download ($ fname, $ fpath = "download /"){

// Transcode UTF-8> gbk if the Chinese file name cannot be detected
$ Filename = iconv ('utf-8', 'gb2312', $ fname); $ path = $ fpath. $ filename; if (! File_exists ($ path) {// check whether the file exists
Echo "the file does not exist! "; Die ();
} $ Fp = fopen ($ path, 'r'); // read-only mode
$ Filesize = filesize ($ path); // file size

// Returned File (stream format)
Header ("Content-type: application/octet-stream"); // returns the value in bytes.
Header ("Accept-Ranges: bytes"); // returns the file size
Header ("Accept-Length: $ filesize"); // The pop-up dialog box of the client, the corresponding file name
Header ("Content-Disposition: attachment; filename = ". $ filename ); // =======================================================
Ob_clean ();
Flush (); // ==========================================================
// Set Traffic Distribution
$ Buffer = 1024; // The byte counter of the specified file.
$ Count = 0; while (! Feof ($ fp) & ($ filesize-$ count> 0) {$ data = fread ($ fp, $ buffer); $ count + = $ data; // count
Echo $ data; // send data to the browser
}

Fclose ($ fp );

}

Download ("testfile.doc");?>

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.