php強制文件下載而非在瀏覽器打開的自定義函數(shù)分享
有時我們希望如圖片、文本文檔、網(wǎng)頁、mp3、pdf等內(nèi)容,當(dāng)點擊對應(yīng)鏈接時直接下載,而不是在網(wǎng)頁上顯示,那么就需要強制設(shè)置header頭信息。以下為一段不會產(chǎn)生亂碼的php函數(shù)實現(xiàn)代碼,其他程序語言也可參考之編寫實現(xiàn)。
/**
* Downloader
*
* @param $archivo
* path al archivo
* @param $downloadfilename
* (null|string) el nombre que queres usar para el archivo que se va a descargar.
* (si no lo especificas usa el nombre actual del archivo)
*
* @return file stream
*/
function download_file($archivo, $downloadfilename = null) {
if (file_exists($archivo)) {
$downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $downloadfilename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($archivo));
ob_clean();
flush();
readfile($archivo);
exit;
}
}
相關(guān)文章
php header函數(shù)的常用http頭設(shè)置
這篇文章主要介紹了php header函數(shù)的常用http頭設(shè)置,本文直接給出代碼實例,代碼中包含詳細(xì)注釋,需要的朋友可以參考下2015-06-06
thinkphp3.2.2前后臺公用類架構(gòu)問題分析
這篇文章主要介紹了thinkphp3.2.2前后臺公用類架構(gòu)問題,以實例形式較為詳細(xì)的分析了前后臺公用類的簡單調(diào)用方法,非常具有實用價值,需要的朋友可以參考下2014-11-11
laravel 使用事件系統(tǒng)統(tǒng)計瀏覽量的實現(xiàn)
今天小編就為大家分享一篇laravel 使用事件系統(tǒng)統(tǒng)計瀏覽量的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10

