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");?>