/** * 文件下载 * @param $filepath 文件路径 为绝对或者相对的物理地址(一定是物理地址); * @param $filename 文件名称 将下载的文件重新命名 */ function file_down($filepath, $filename = '') { if(!$filename) $filename = basename($filepath); if(is_ie()) $filename = rawurlencode($filename); $filetype = fileext($filename); $filesize = sprintf("%u", filesize($filepath)); if(ob_get_length() !== false) @ob_end_clean(); header('Pragma: public'); header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: pre-check=0, post-check=0, max-age=0'); header('Content-Transfer-Encoding: binary'); header('Content-Encoding: none'); header('Content-type: '.$filetype); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-length: '.$filesize); readfile($filepath); exit; } /** * 取得文件扩展 * @param $filename 文件名 * @return 扩展名 */ function fileext($filename) { return strtolower(trim(substr(strrchr($filename, '.'), 1, 10))); } /** * IE浏览器判断 */ function is_ie() { $useragent = strtolower($_SERVER['HTTP_USER_AGENT']); if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false; if(strpos($useragent, 'msie ') !== false) return true; return false; } /** * 产生随机字符串 * * @param int $length 输出长度 * @param string $chars 可选的 ,默认为 0123456789 * @return string 字符串 */ function random($length, $chars = '0123456789') { $hash = ''; $max = strlen($chars) - 1; for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; }
用法:
//$filename为相对的或者绝对的物理地址,不能是http地址,否则出错
$basefilename = basename($filename);
$ext = fileext($basefilename);
$basefilename = date(‘Ymd_his’).random(3).’.’.$ext;
file_down($filename, $basefilename);