Tag: download

用PHP实现文件下载

没有评论

2010 年 10 月 12 日 at 下午 2:03分类:PHP | WEB开发

//简单的用header头实现文件下载的例子:

<?php
// We’ll be outputting a PDF
header(‘Content-type: application/pdf’);

// It will be called downloaded.pdf
//header(‘Content-Disposition: attachment; filename=”downloaded.pdf”‘);

// The PDF source is in original.pdf
readfile(‘original.pdf’);
?>

//将整个过程写成一个函数如下:

<?php
function dl_file($file,$tag = true){
if (!is_file($file) ) { die(“404 File not found!”); }
$way = $tag ? ‘attachment’ : ‘inline’; //attachment就是以附件的方式打开,inline就是在线打开
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,”.”),1));

switch( $file_extension ) {
case “pdf”: $ctype=”application/pdf”; break;
case “exe”: $ctype=”application/octet-stream”; break;
case “zip”: $ctype=”application/zip”; break;
case “doc”: $ctype=”application/msword”; break;
case “xls”: $ctype=”application/vnd.ms-excel”; break;
case “ppt”: $ctype=”application/vnd.ms-powerpoint”; break;
case “gif”: $ctype=”image/gif”; break;
case “png”: $ctype=”image/png”; break;
case “jpeg”:
case “jpg”: $ctype=”image/jpg”; break;
case “mp3″: $ctype=”audio/mpeg”; break;
case “wav”: $ctype=”audio/x-wav”; break;
case “mpeg”:
case “mpg”:
case “mpe”: $ctype=”video/mpeg”; break;
case “mov”: $ctype=”video/quicktime”; break;
case “avi”: $ctype=”video/x-msvideo”; break;

//The following are for extensions that shouldn’t be downloaded (sensitive stuff, like php files)
case “php”:
case “htm”:
case “html”:
case “txt”: die(“Cannot be used for “. $file_extension .” files!”); break;

default: $ctype=”application/force-download”;
}
//Begin writing headers
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”);

//Use the switch-generated Content-Type
header(“Content-Type: $ctype”);

//Force the download
//关键的参数就是Content-Disposition:$way
//$way的值为attachment就是以附件的方式打开
//$way的值为inline就是在线打开
$header=”Content-Disposition: “.$way.”; filename=”.$filename.”;”;
header($header );
header(“Content-Transfer-Encoding: binary”);
header(“Content-Length: “.$len);
@readfile($file);
exit;
}
dl_file(“original.pdf”);
?>