PHP文件下載

<?php
    class Down
    {
        private $file = '';
        private $msg = null;


        public function __construct($file,$buffer=1024)
        {
            // 用以解決中文不能顯示出來的問題
            $file            = iconv('utf-8','gbk',$file);
            $this->file      = $_SERVER['DOCUMENT_ROOT'].'/'.$file;
            $this->buffer    = $buffer;
        }


        public function act()
        {
            if (!file_exists($this->file)) 
            {
                // 若是須要下載的文件不存在
                $this->msg = '文件不存在';
                return $this->msg;
            }


            $handle = fopen($this->file,'r');
            if (!$handle) 
            {
                // 沒法打開文件
                $this->msg = '沒法打開文件';
                return $this->msg;
            }


            $filesize = filesize($this->file);


            // 下載須要的文件頭
            header('content-type:application/ocet-stream');
            header('Accept-Ranges:bytes');
            header('Accept-Length:'.$filesize);
            header('Content-Disposition:attachment;filename='.$this->file);


            $file_count = 0;


            // 向瀏覽器返回數據
            while(!feof($handle) && $file_count<$filesize){
                $file_down = fread($handle,$this->buffer);
                $file_count += $this->buffer;
                echo $file_down;
            }


            // 關閉資源
            fclose($handle);
            $msg = '下載完畢';
            // return $msg;
            return $file_down;
        }
    }
header('content-type:text/html;charset="utf-8"');
header('expire:-1');
header('cache-control:no-cache');
header("pragma:no-cache");
$down = new Down('d:/myblog/test.jpg');
$msg = $down->act();
echo $msg;
?>
相關文章
相關標籤/搜索