The PHP documentation provides a nice example:
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
EDIT (Response to comment, explanation)
header('Content-Description: File Transfer');
Do not display in the browser, but transfer the file.
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
File is a binary file.
Browsers generally download binary files, unless they can display them.
header('Content-Disposition: attachment; filename='.basename($file));
Make the download dialog show the proper file name.
Note: You can use any file name.
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
File should not be cached by the browser.
Cache could cause trouble in case of dynamic content.
header('Content-Length: ' . filesize($file));
Send the correct file size to the browser,
otherwise the browser is unable to estimate the transfer-time.
ob_clean();
flush();
Make sure the headers are send to the browser before the download starts.
readfile($file);
Send the file to the browser.
exit;
Done :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…