>  기사  >  php教程  >  PHP使用文件流下载文件方法(附:解决下载文件内容乱码问题),

PHP使用文件流下载文件方法(附:解决下载文件内容乱码问题),

WBOY
WBOY원래의
2016-06-13 09:27:401388검색

PHP使用文件流下载文件方法(附:解决下载文件内容乱码问题),

记得高中时候做过游戏私服,那时候的游戏主页是用PHP写的,因为文件很固定,客户端,登陆器和一些小工具,文件数目也不是很多,所以都是直接把下载链接写死的,直接链接到本地服务器的文件目录,今天QQ群有个朋友突然问我用文件流做PHP下载功能,顺手写了个小Demo,代码很简单,注释也全,直接上代码吧~

 

1、flush — 刷新输出缓冲

2、ob_clean — 清空(擦掉)输出缓冲区

此函数用来丢弃输出缓冲区中的内容。

此函数不会销毁输出缓冲区,而像 ob_end_clean() 函数会销毁输出缓冲区。

注:上面2个函数可以解决PHP下载文件内容乱码

 

<?<span>php

    </span><span>//</span><span>fname为要下载的文件名
    //$fpath为下载文件所在文件夹,默认是downlod</span>
    <span>function</span> download(<span>$fname</span>,<span>$fpath</span>="download/"<span>){

        </span><span>//</span><span>避免中文文件名出现检测不到文件名的情况,进行转码utf-8->gbk</span>
        <span>$filename</span>=<span>iconv</span>('utf-8', 'gb2312', <span>$fname</span><span>);
        </span><span>$path</span>=<span>$fpath</span>.<span>$filename</span><span>;
        </span><span>if</span>(!<span>file_exists</span>(<span>$path</span>)){<span>//</span><span>检测文件是否存在</span>
            <span>echo</span> "文件不存在!"<span>;
            </span><span>die</span><span>();
        }

        </span><span>$fp</span>=<span>fopen</span>(<span>$path</span>,'r');<span>//</span><span>只读方式打开</span>
        <span>$filesize</span>=<span>filesize</span>(<span>$path</span>);<span>//</span><span>文件大小

        //返回的文件(流形式)</span>
        <span>header</span>("Content-type: application/octet-stream"<span>);
        </span><span>//</span><span>按照字节大小返回</span>
        <span>header</span>("Accept-Ranges: bytes"<span>);
        </span><span>//</span><span>返回文件大小</span>
        <span>header</span>("Accept-Length: <span>$filesize</span>"<span>);
        </span><span>//</span><span>这里客户端的弹出对话框,对应的文件名</span>
        <span>header</span>("Content-Disposition: attachment; filename=".<span>$filename</span><span>);
        </span><span>//</span><span>================重点====================</span>
        <span>ob_clean</span><span>();
        </span><span>flush</span><span>();
        </span><span>//</span><span>=================重点===================
        //设置分流</span>
        <span>$buffer</span>=1024<span>;
        </span><span>//</span><span>来个文件字节计数器</span>
        <span>$count</span>=0<span>;
        </span><span>while</span>(!<span>feof</span>(<span>$fp</span>)&&(<span>$filesize</span>-<span>$count</span>>0<span>)){
            </span><span>$data</span>=<span>fread</span>(<span>$fp</span>,<span>$buffer</span><span>);
            </span><span>$count</span>+=<span>$data</span>;<span>//</span><span>计数</span>
            <span>echo</span> <span>$data</span>;<span>//</span><span>传数据给浏览器端</span>
<span>        }

        </span><span>fclose</span>(<span>$fp</span><span>);

    }


    download(</span>"CGEX脚本清单.doc"<span>);



</span>?>

 

 

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.