php中强制下载文件的代码(解决了IE下中文文件名乱码问题)

yipeiwu_com5年前PHP代码库
中间遇到一个问题是提交的中文文件名直接放到header里在IE下会变成乱码,解决方法是将文件名先urlencode一下再放入header,如下。
复制代码 代码如下:

<?php
$file_name = urlencode($_REQUEST['filename']);
header("Pragma: public"); header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment; filename='.$file_name);
echo stripslashes($_REQUEST['content']);
?>


解决PHP Header下载文件在IE文件名中文乱码有两种常见的,一种是是把页面编码改成utf8,另一种是对中文url进入urlencode编码就可以解决了。
解决方案一(我的页面是utf-8编码):

复制代码 代码如下:

$filename = "中文.txt";
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
header('Content-Type: application/octet-stream');
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8''' . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}


解决方法二

将文件名先urlencode一下再放入header,如下。
代码如下:

复制代码 代码如下:
<?php
$file_name = urlencode($_REQUEST['filename']);
header("Pragma: public"); header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: attachment; filename='.$file_name);
echo stripslashes($_REQUEST['content']);
?>

相关文章

PHP积分兑换接口实例

本文实例讲述了PHP积分兑换接口的实现方法。分享给大家供大家参考。具体实现方法如下: exchange.php接口内容如下: 复制代码 代码如下:<?php ...

比较详细PHP生成静态页面教程

一,PHP脚本与动态页面。   PHP脚本是一种服务器端脚本程序,可通过嵌入等方法与HTML文件混合,也可以类,函数封装等形式,以模板的方式对用户请求进行处理。无论以何种方式,它的基本原...

php不用GD库生成当前时间的PNG格式图象的程序第1/2页

<?php function set_4pixel($r, $g, $b, $x, $y) { global $sx, $sy, $pixels; $ofs = 3 * ($sx...

php错误、异常处理机制(补充)

一、错误处理 异常处理: 意外,是在程序运行过程中发生的意料这外的事,使用异常改变脚本正常流程 PHP5中的一个新的重要特性 复制代码 代码如下: if(){ }else{ } try...

php通过session防url攻击方法

本文实例讲述了php通过session防url攻击方法。分享给大家供大家参考。具体实现方法如下: 通过session跟踪,可以很方便地避免url攻击的发生,php采用session防ur...