文件下载


function dl_file($file){
//这是下载文件的函数,$file是文件路径.
//First, see if the file exists
if (!is_file($file)) { die("<b>404 File not found!</b>"); }

//Gather relevent info about file
$len = filesize($file); //则返回文件大小的字节数。若失败,则返回 false 并生成一条 E_WARNING 级的错误。
$filename = basename($file); //返回路径中的文件名部分。
//图片的格式(JPG)换成小写 strtolower(把所有大写换成小写)
$file_extension = strtolower(substr(strrchr($filename,"."),1)); //strrchr() 函数(在php中)查找字符在指定字符串中从左面开始的最后一次出现的位置,如果成功,返回该字符以及其后面的字符,如果失败,则返回 NULL。

//This will set the Content-Type to the appropriate setting for the file
switch( $file_extension ) {
case "pdf": $ctype="application/pdf"; break; ////break是结束整个循环体,continue是结束单次循环
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; case "php": case "htm": case "html": case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break; default: $ctype="application/force-download"; }
原文地址:https://www.cnblogs.com/taikongliu/p/6281557.html