PHP using file stream to download file method

Source: Internet
Author: User
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");?>

  • 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.