1. 程式人生 > >實現php檔案安全下載

實現php檔案安全下載

實現php檔案安全下載!


public function down(){

           $file_name = $_REQUEST['file'];
           $file_dir = "/目錄/";
           $dir = $_SERVER['DOCUMENT_ROOT'];
           $path = $dir . $file_dir . $file_name; //要寫絕對路徑。不能寫相對路徑
            
            if (!file_exists($path)) { //檢查檔案是否存在
            echo "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
            echo "檔案找不到";
            exit;
            } else {
            $file = fopen($path,"r"); // 開啟檔案
            // 輸入檔案標籤
            Header("Pragma: public");
            Header("Expires: 0");
            Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            Header("Cache-Control: public");
            Header("Content-Description: File Transfer");
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: ".filesize($path));
            Header("Content-Disposition: attachment; filename=" . $file_name);
            // 輸出檔案內容
 
           echo fread($file,filesize($path));
          
            fclose($file);
            exit();
            }

}