php下载文件的代码示例

php下载文件的代码,如下:

 1 复制代码 代码如下:

 2 

 3 <?php 

 4 //下载文件

 5 $file = 'monkey.gif';

 6 

 7 if (file_exists($file)) { 

 8 header('Content-Description: File Transfer'); 

 9 header('Content-Type: application/octet-stream'); 

10 header('Content-Disposition: attachment; filename='.basename($file)); 

11 header('Content-Transfer-Encoding: binary'); 

12 header('Expires: 0'); 

13 header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 

14 header('Pragma: public'); 

15 header('Content-Length: ' . filesize($file)); 

16 ob_clean(); 

17 flush(); 

18 readfile($file); 

19 exit;  //by www.jbxue.com

20 } 

21 ?>

以上代码是下载代码。

附,在线预览pdf文件的代码,买一送一了,哈哈。 

<?php

//在线预览pdf文件

//by www.jbxue.com

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('Cache-Control: public'); // needed for i.e. 

header('Content-Type: application/pdf'); 

header('Content-Disposition: inline; filename="sample.pdf"'); 

readfile($attachment_location); 

die(); // stop execution of further script because we are only outputting the pdf



} else { 

die('Error: File not found.'); 

} 

} 

?>

你可能感兴趣的:(下载文件)