Heim > Artikel > Backend-Entwicklung > php文件下载代码_PHP教程
$f_id =isset($_GET['id'])?$_GET['id']:'';
$t_id =isset($_GET['tid'])?$_GET['tid']:'';
$t_na =($t_id==1)?"su_photo":"su_video";
if($t_id==1){
$t_na='su_photo';
}else if($t_id==2){
$t_na='su_video';
}else{
$t_na='su_cert';
}
$sql ="select * from $t_na where id=$f_id and uid='".$_SESSION['xm']."' ";
$result =mysql_query($sql) or exit("system busy...");
if(!mysql_num_rows($result)){exit("
alert('记录不存在!');history.back();
");}
$rs =mysql_fetch_object($result);
$file_name=substr($rs->path,strrpos($rs->path,"/")+1);
$file_dir =substr($rs->path,0,strlen($rs->path)-strlen($file_name));
$file_dir=realpath(str_replace('../','',$file_dir))."\";
$rpath=$file_dir.$file_name;
if (!file_exists($rpath)) { //检查文件是否存在
exit("
alert('文件找不到!');history.back();
");
} else {
$tent=substr($rpath,strrpos($rpath,".")+1);
$file = fopen($rpath,"r"); // 打开文件
Header("Content-type: ".headertype($tent)."");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . $file_name);
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit("
alert('下载完毕!');history.back();
");
}
function headertype($type){
switch($type){
case 'gif':
return 'image/gif';
break;
case 'jpg':
return 'image/pjpeg';
break;
case 'bmp':
return 'image/bmp';
break;
case 'png':
return 'image/x-png';
break;
case 'txt':
return 'application/octet-stream';
break;
case 'zip':
return 'application/x-zip-compressed';
break;
case 'rar':
return 'application/x-rar-compressed';
break;
case 'doc':
return 'application/msword';
break;
case 'swf':
return 'application/x-shockwave-flash';
break;
case 'wma':
return 'audio/x-ms-wma';
break;
case 'rm':
return "application/vnd.rn-realmedia";
break;
case 'mp3':
return "audio/mp3";
break;
default:
return 'text/plain';
}
}
?>