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

Code example for php download file

高洛峰
Release: 2023-03-04 07:30:01
Original
1254 people have browsed it

<?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; 
} 
?>
Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template