PHP-强制文件下载 (Force download)
时间:2009-03-25 来源:renxiao2003
在APACHE经过SSL加密后,原来下载文件(如XLS)的代码,在原来好用的情况下,出现“Internet Explorer 无法下载 **.php (来自**网站)。Internet Explorer无法打开该 internet 网站。请求的网站不可用,或找不到,请以后再试。 ”提示,而且下载的不是我们指定的文件,好像是在下载PHP源文件了。
使用下面的方法经验证后可用:
<?php
/**
* Force a file to be download instead of displayed.
*/
function force_download ($filePath, $name, $mimetype = '') {
// File's mimetype is not set?
if (empty($mimetype)) {
$mimetype = 'application/octet-stream';
}
// Start sending headers
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Transfer-Encoding: binary");
header("Content-Type: " . $mimetype);
header("Content-Length: " . filesize($filePath));
header("Content-Disposition: attachment; filename='" . $name . "';" );
//read data
readfile($filePath);
exit();
}
?> 代码来自网站:http://phparch.cn/index.php/php/34-basics/52-force-download 而http://www.jb51.net/article/15553.htm这里提到的方法似乎行不通。(我测试没通过)。
/**
* Force a file to be download instead of displayed.
*/
function force_download ($filePath, $name, $mimetype = '') {
// File's mimetype is not set?
if (empty($mimetype)) {
$mimetype = 'application/octet-stream';
}
// Start sending headers
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Transfer-Encoding: binary");
header("Content-Type: " . $mimetype);
header("Content-Length: " . filesize($filePath));
header("Content-Disposition: attachment; filename='" . $name . "';" );
//read data
readfile($filePath);
exit();
}
?> 代码来自网站:http://phparch.cn/index.php/php/34-basics/52-force-download 而http://www.jb51.net/article/15553.htm这里提到的方法似乎行不通。(我测试没通过)。
相关阅读 更多 +