Home >Backend Development >PHP Tutorial >Code example for php download file

Code example for php download file

高洛峰
高洛峰Original
2016-12-23 12:46:111265browse

<?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; 
} 
?>

The above code is the download code
Then I will post a code to preview the pdf file online

<?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;); 
} 
} 
?>

For more code examples of PHP download files and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn