[php]文件下载简述

文件下载是通过网页页面链接跳转到后台php脚本处理,前台跳转链接代码如下:

<a href="download.php?filename=hello.txt">download</a>

后台处理脚本

<?php
    /*
        @param $file_name: filename
        @paramp $file_sub_path: file sub path
        @function download file
    */
    function down_file($file_name)
    {
        /*convert encode*/
        $file_name = iconv("utf-8", "gb2312", $file_name);
        $file_path = $_SERVER['DOCUMENT_ROOT'].$file_sub_path.$file_name;
        if(!file_exists($file_path))
        {
            echo "file not exist!</br>";
            return;
        }
        $fp = fopen($file_path, "r");

        /*get file length*/
        $file_size = filesize($file_path);

        /*change protocal to tell browser is download*/

        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: $file_size");
        header("Content-Disposition: attachment; filename=".$file_name);

        /*transpot to brower*/
        /*file buffer*/
        $buffer = 10240;
        /*file counter*/
        $file_count = 0;
        while(!feof($fp) && ($file_size-$file_count>0))
        {
            $data = fread($fp, $buffer);
            $file_count+=$buffer;
            echo $data;
        }

        /*close file*/
        fclose($fp);
    }
    $file_name = $_REQUEST['filename'];
    down_file($file_path);
?>

 

下载文件需要的四个header
//告诉返回文件的类型,application/octet-stream表示不知道类型,为二进制流
header("Content-type:application/octet-stream");
//按字节返回
header("Accept-Ranges:bytes");
//返回文件的大小
header("Accept-Length:$file_size");
//返回的文件名称
header("Content-Disposition:attachment; filenae=".filename);

posted @ 2015-02-04 15:53  风痕影默  阅读(132)  评论(0编辑  收藏  举报
友情链接:极限BT