PHP header()函數實現文件下載功能

<?php
/**
 * 文件下載類
 */
class Download extends Controller
{
 	/**
     * @explain 構造方法 繼承父類構造方法
     *              備註: 如果沒登陸則到登陸頁面 否則則進入WIKI前端登錄頁面
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->con_checkLoginAndTodo();
        $this->client_url();//整站URL
    }

    /**
     * 文件下載方法
     */
    public function index()
    {
    	$path = get_param('path');//get_param()函數是一個獲取post或get方式傳過來的參數
        $firstNum = strpos($path, './uploadfile/');//查找字符串首次出現的位置
        $urlStr = substr($path,0,$firstNum);
        $decodePath = base64_decode($urlStr);
        $url = $decodePath.substr($path,$firstNum);
    	if(file_exists($url))//檢查文件或目錄是否存在
    	{
			header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename='.basename($url));
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($url));
		    ob_clean();
    		// flush();
	    	readfile($url);
	    	exit;
    	}else{
    		echo "<script>alert('文件不存在!');history.back(-1);</script>";
    	}
    }
}
?>
可以下載任何格式的文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章