验证用户权限后调用此函数可以下载文件,文件可以放在任意位置。
客户端不会出现乱码
不会知道所下载文件真实路径。
/**
* 下载文件
* @param string $file
* 被下载文件的路径
* @param string $name
* 用户看到的文件名
*/
function download($file,$name=''){
$filename = $name ? $name : pathinfo($file,pathinfo_filename);
$filepath = realpath($file);
$fp = fopen($filepath,'rb');
if(!$filepath || !$fp){
header('http/1.1 404 not found');
echo error: 404 not found.(server file path error);
exit;
}
$filename = $filename .'.'. pathinfo($filepath,pathinfo_extension);
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace(+, %20, $encoded_filename);
header('http/1.1 200 ok');
header( pragma: public );
header( expires: 0 );
header(content-type: application/octet-stream);
header(content-length: .filesize($filepath));
header(accept-ranges: bytes);
header(accept-length: .filesize($filepath));
$ua = $_server[http_user_agent];
if (preg_match(/msie/, $ua)) {
header('content-disposition: attachment; filename=' . $encoded_filename . '');
} else if (preg_match(/firefox/, $ua)) {
header('content-disposition: attachment; filename*=utf8\'\'' . $filename . '');
} else {
header('content-disposition: attachment; filename=' . $filename . '');
}
// ob_end_clean(); // 输出文件内容
fpassthru($fp);
exit;
}
ad:真正免费,域名+虚机+企业邮箱=0元