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

yipeiwu_com6年前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']);
?>

相关文章

php5.2以下版本无json_decode函数的解决方法

今天写代码的时候,需要用到json_decode函数,发现php5.2以前的版本没有集成这个函数,不过我们可以通过自定义函数实现。 复制代码 代码如下:function json_dec...

使用GDB调试PHP代码,解决PHP代码死循环问题

最近在帮同事解决Swoole Server问题时,发现有1个worker进程一直处于R的状态,而且CPU耗时非常高。初步断定是PHP代码中发生死循环。 下面通过一段代码展示如何解决PHP...

php简单检测404页面的方法示例

php简单检测404页面的方法示例

本文实例讲述了php简单检测404页面的方法。分享给大家供大家参考,具体如下: 需求描述: 检测给定的url是否是404页面。 方式一: 使用file_get_contents函数,可以...

php一句话cmdshell新型 (非一句话木马)

php一句话cmdshell新型 (非一句话木马)

复制代码 代码如下:<?php /*一个新型的php一句话cmdshell(非一句话木马) //原理:php运行时如果遇见字符``(键盘上~符号的下档键)总会尝试着执行``里面包含...

php实现的表单验证类完整示例

本文实例讲述了php实现的表单验证类。分享给大家供大家参考,具体如下: <?php /** * 用法 * use Validate\Validator; *...