PHP下载文件(二)

其中的$filepath为文件路径,$loadname 为下载文件的名字,或者是自己定义的名字

if(headers_sent()){

die("headers Sent");
}
$loadName = !empty($loadName) ? $loadName : time();
$info = get_headers($filePath);
if(in_array('HTTP/1.1 200 OK', $info)){
//取出传过来文件的大小
$loadName = iconv("UTF-8", "GBK" , $loadName);
$fsize = $info['5'];
//截取文件的后缀名
$path_part = explode('.', $filePath);
$ext = end($path_part);
$ext = strtolower($ext);
switch($ext){
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 "docx": $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":$ctype="image/jpeg";break;
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header('Pragma: public');
//最后修改的时间
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
//max-age=5 在5秒之内就不会访问服务器
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
//加载您要下载的URL
header('Content-Transfer-Encoding: binary');
header('Content-Encoding: none');
//设置文件的类型
header('Content-type: '.$ctype);
//basename 返回路径中文件名的部分
header("Content-Disposition: attachment;filename=\"".$loadName."\";" );//文件名称
//设置文件的大小
// header('Content-length:'.$fsize);
header($fsize);
readfile($filePath);
}else{
die("未找到文件!");
}

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