Rumah >pembangunan bahagian belakang >tutorial php >PHP实现多种格式文件下载并解决乱码问题
这几天写项目,遇到一个问题,一般的文件下载还好说,但是如果是中文且有多种格式的文件下载就比较棘手,调了很久的BUG,
终于完成,其中需要注意以下几点:
1.对于文件名是中文的文件,要记得转码,防止中文乱码的发生,因为大部分的主机的编码是GB2312的,而我们用的是UTF-8,
所以在操作之前要用iconv()函数进行转码,防止找不到文件而报错。
2.需要对所要下载的文件的格式进行判断,根据格式再写header()函数。
具体代码如下:
<?php header("Content-type:text/html;charset=utf-8"); $filename = "大学英语选课说明.docx"; //文件名 $filename = iconv("utf-8","gb2312//IGNORE",$filename); //转码 $file = "upload/".$filename; //文件路径 $len = filesize($file); //文件大小 $file_extension = strtolower(substr(strrchr($filename,"."),1)); //文件后缀名 switch( $file_extension ) //判断文件类型 { case "pdf": $ctype="application/pdf"; break; case "exe": $ctype="application/octet-stream"; break; case "zip": $ctype="application/zip"; break; case "docx": 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": die("<b>Cannot be used for ". $file_extension ." files!"); break; default: $ctype="application/force-download"; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Type: $ctype"); $header="Content-Disposition: attachment; filename=".$filename.";"; header($header); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".$len); readfile($file); ?>
<?php <span style="white-space:pre"> $ua = $_SERVER["HTTP_USER_AGENT"]; <span style="white-space:pre"> </span>$filename = "中文 文件名.txt"; <span style="white-space:pre"> </span>$encoded_filename = urlencode($filename); <span style="white-space:pre"> </span>$encoded_filename = str_replace("+", "%20", $encoded_filename); <span style="white-space:pre"> </span>header('Content-Type: application/octet-stream'); <span style="white-space:pre"> </span>if (preg_match("/MSIE/", $ua)) { <span style="white-space:pre"> </span>header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); <span style="white-space:pre"> </span>} else if (preg_match("/Firefox/", $ua)) { <span style="white-space:pre"> </span>header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"'); <span style="white-space:pre"> </span>} else { <span style="white-space:pre"> </span>header('Content-Disposition: attachment; filename="' . $filename . '"'); <span style="white-space:pre"> </span>} ?>
产生的乱码错误,我认为,转码后中文乱码的问题基本就解决了。
本人经验,仅供参考!
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了PHP实现多种格式文件下载并解决乱码问题,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。