我想要一個php腳本來下載任何類型的文件而不打開它。我發現了以下功能,在我看來有點不同,但我不知道哪個更好。請讓我知道哪一個更好,可靠:PHP強制瀏覽器下載文件(兩種方式)
-
$file = 'monkey.gif'; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; }
從其他教程:
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-Disposition: attachment; filename=\"{$file->filename}\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . $filesize); // download // @readfile($file_path); $dwn_file = @fopen($file_path,"rb"); if ($dwn_file) { while(!feof($dwn_file)) { print(fread($dwn_file, 1024*8)); flush(); if (connection_status()!=0) { @fclose($dwn_file); die(); } } @fclose($dwn_file); }