我在一個很好的「強制下載文件」腳本上工作,目的是確保提供下載文件而不是顯示在瀏覽器中,無論文件類型是什麼。強制下載腳本
它曾經運行良好,但最近我收到反饋,它不會工作,特別是對於PDF和xls文件(MS Excel)。在PDF的情況下,該文件被檢測爲「無效」,或者在xls文件的情況下,該文件在其內容的頂部獲得部分html文件目錄頁面。
我的功能到底出了什麼問題?
這是它。請注意,它可以使用url或本地路徑工作。
function offerToDownloadFile($filename, $access_type='url') {
/*
PHP FORCE DOWNLOAD SCRIPT
*/
// required for IE, otherwise Content-disposition is ignored
if (ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
if($access_type === 'url') {
// access type is via the file 's url
$parsed_url = parse_url($filename);
$fileinfo = pathinfo($filename);
$parsed_url['extension'] = $fileinfo['extension'];
$parsed_url['filename'] = $fileinfo['basename'];
$parsed_url['localpath'] = LOCALROOT . $parsed_url['path'];
}
else {
// access type is the local file path
$fileinfo = pathinfo($filename);
$parsed_url['localpath'] = $filename;
$parsed_url['filename'] = basename($filename);
$parsed_url['extension'] = $fileinfo['extension'];
}
// just in case there is a double slash created when joining document_root and path
$parsed_url['localpath'] = preg_replace('/\/\//', '/', $parsed_url['localpath']);
if (!file_exists($parsed_url['localpath'])) {
die('File not found: ' . $parsed_url['localpath']);
}
$allowed_ext = array('ics','pdf', 'png', 'jpg', 'jpeg', 'zip', 'doc', 'xls', 'gif', 'exe', 'ppt','ai','psd','odt');
if (!in_array($parsed_url['extension'], $allowed_ext)) {
die('This file type is forbidden.');
}
switch ($parsed_url['extension']) {
case "ics": $ctype="text/calendar";
break;
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;
default: $ctype = "application/force-download";
}
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-Type: $ctype");
header("Content-Disposition: attachment; filename=\"" . $parsed_url['filename'] . "\";");
header("Content-Transfer-Encoding: binary");
// header("Content-Length: " . filesize($parsed_url['localpath']));
readfile($parsed_url['localpath']);
clearstatcache();
die();
exit();
}
你有什麼瀏覽器這個問題?這是全部嗎? – Pasta 2009-10-09 10:32:35
也使用'application/octet-stream'作爲默認媒體類型。 – Gumbo 2009-10-09 12:16:48