此代码片断可用于任意文件下载, 包括图片和HTML文件.
This codesnippet can be used to force a download of any type of file, including images and HTML pages.
<?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();
}
?>