[php]檔案下載簡述

風痕影默發表於2015-02-04

檔案下載是通過網頁頁面連結跳轉到後臺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);

相關文章