PHP using file stream to download file method
?
?
PHP using file stream to download file method
?
?
1、flush — 刷新输出缓冲2、ob_clean — 清空(擦掉)输出缓冲区注:上面2个函数可以解决PHP下载文件内容乱码
DEMO:
//fname is the file name to download //$fpath is the folder where the files are downloaded, the default is Downlod function download($fname,$fpath="download/"){ //Avoid Chinese file name in case of file name not detected, transcoding UTF-8->GBK $filename=iconv (' Utf-8 ',' gb2312 ',$fname);$path=$fpath.$filename;if(!file_exists ($path)){//Detect if 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");//return by byte sizeHeader"Accept-ranges:bytes");//Return file sizeHeader"Accept-length: $filesize");//Here the client's popup dialog box, corresponding to the file nameHeader"content-disposition:attachment; Filename= ".$filename);//================ Key ====================Ob_clean (); Flush ();//================= Key =================== //Set shunt $buffer=1024x768;//A file byte counter $count=0; while(!feof ($fp) && ($filesize-$count>0)){$data=fread ($fp,$buffer);$count+=$data;//Count Echo $data;//Transmit data to browser side} fclose ($fp); } Download ("Testfile.doc");?>