首頁 >後端開發 >php教程 >php下載檔案的程式碼範例

php下載檔案的程式碼範例

高洛峰
高洛峰原創
2016-12-23 12:46:111265瀏覽

<?php 
$file = &#39;monkey.gif&#39;; 

if (file_exists($file)) { 
header(&#39;Content-Description: File Transfer&#39;); 
header(&#39;Content-Type: application/octet-stream&#39;); 
header(&#39;Content-Disposition: attachment; filename=&#39;.basename($file)); 
header(&#39;Content-Transfer-Encoding: binary&#39;); 
header(&#39;Expires: 0&#39;); 
header(&#39;Cache-Control: must-revalidate, post-check=0, pre-check=0&#39;); 
header(&#39;Pragma: public&#39;); 
header(&#39;Content-Length: &#39; . filesize($file)); 
ob_clean(); 
flush(); 
readfile($file); 
exit; 
} 
?>

以上程式碼是下載程式碼 
接下來貼一段線上預覽pdf檔的程式碼 

<?php 
public function fddAction() 
{ 
// get attachment location 
$attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/pdf/fdd/sample.pdf"; 

if (file_exists($attachment_location)) { 
// attachment exists 

// send open pdf dialog to user 
header(&#39;Cache-Control: public&#39;); // needed for i.e. 
header(&#39;Content-Type: application/pdf&#39;); 
header(&#39;Content-Disposition: inline; filename="sample.pdf"&#39;); 
readfile($attachment_location); 
die(); // stop execution of further script because we are only outputting the pdf 

} else { 
die(&#39;Error: File not found.&#39;); 
} 
} 
?>

更多php下載檔案的程式碼範例相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn