如何用php实现文件强制下载呢?本节分享下具体的实现方法与代码。
首先,看 xls 文件的下载: 
 
如果不加第一句,会弹出 : Internet Explorer 无法下载 **.php (来自**网站)。Internet Explorer无法打开该 internet 网站。请求的网站不可用,或找不到,请以后再试。
而且连名字都不是所设的名字:report.xls,而是 **.php,把第一句加上就可以了。
在看 rar,gif 之类的,不加第一句,居然通过,不弹出那个错误框框!
如果是 gif等图片的话 ,Content-Disposition:attachment; 会强制弹出一个保存对话框。如果省略或是 inline 就会直接在网页里显示。
Content-type 应取值,如下:
 
switch( $file_extension ) { 
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 "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;
//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files) 
case "php": 
case "htm": 
case "html": 
case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;
default: $ctype="application/force-download"; 
}