Remember when high school played a game, then the game homepage is written in PHP, because the file is very fixed, the client, the lander and some small tools, the number of files is not many, so are directly to the download link to death, directly linked to the local server file directory, Today QQ Group has a friend suddenly asked me to use file stream php download function, handy to write a small demo, code is very simple, comments are all, directly on the Code bar ~
1. flush- Refresh Output Buffer
2. ob_clean- Empty (erase) output buffer
This function is used to discard the contents of the output buffer.
This function does not destroy the output buffer, and the like ob_end_clean () function destroys the input buffer.
Note: The above 2 functions can solve the contents of PHP download file garbled
<?PHP//fname is the file name to download//$fpath as the folder where the files are downloaded, the default is Downlod functionDownload$fname,$fpath= "download/"){ //avoid the Chinese file name when the file name is not detected in the case of transcoding UTF-8->GBK $filename=Iconv(' Utf-8 ', ' gb2312 ',$fname); $path=$fpath.$filename; if(!file_exists($path)){//detects if a file exists Echo"File does not exist!" "; die(); } $fp=fopen($path, ' R ');//read-only mode open $filesize=filesize($path);//file size//returned file (stream form) Header("Content-type:application/octet-stream"); //returns by byte size Header("Accept-ranges:bytes"); //return file Size Header("Accept-length:$filesize"); //here the client's popup dialog box, corresponding to the file name Header("Content-disposition:attachment; Filename= ".$filename); //================ Key ==================== Ob_clean(); Flush(); //================= key ===================//Set shunt $buffer=1024; //a file byte counter. $count=0; while(!feof($fp) && ($filesize-$count>0)){ $data=fread($fp,$buffer); $count+=$data;//Count Echo $data;//Pass data to the browser side } fclose($fp); } Download ("Cgex script list. doc");?>