PHP Method for downloading files using file streams (Appendix: Solve the Problem of garbled characters in the downloaded file content ),
I remember that I used private game servers in high school. At that time, the game homepage was written in PHP. Because the files were fixed, the client, the login device, and some gadgets, the number of files was not large, therefore, the download link is directly written to the file directory of the local server. Today, a friend in the QQ group suddenly asked me to use the file stream for PHP download, I wrote a small Demo. The code is simple and the comments are complete. Just go to the code ~
1. flush-refresh the output buffer
2. ob_clean-clear (erase) output buffer
This function is used to discard the content in the output buffer.
This function will not destroy the output buffer, but the function like ob_end_clean () will destroy the output buffer.
Note: The above two functions can solve the problem of garbled characters in PHP download files.
<? Php // fname indicates the name of the file to be downloaded. // $ fpath indicates the folder where the file to be downloaded is located. The default value is downlevels function download ($ fname, $ fpath = "download /") {// if the Chinese file name cannot be detected, transcode UTF-8> gbk $ filename = iconv ('utf-8', 'gb2312', $ fname ); $ path = $ fpath. $ filename; if (! File_exists ($ path) {// check whether the echo file exists. "The file does not exist! "; Die () ;}$ fp = fopen ($ path, 'R'); // open $ filesize = filesize ($ path) in read-only mode ); // file size // returned file (stream form) header ("Content-type: application/octet-stream"); // return header ("Accept-Ranges: bytes "); // return the file size header (" Accept-Length: $ filesize "); // In the displayed dialog box on the client, the corresponding file name header (" Content-Disposition: attachment; filename = ". $ filename ); // ============================================================== ob_clean (); flush (); // ============================ ================/// Set the shunting $ buffer = 1024; // bytes counter for the next 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 ("cgexscript example .doc");?>