php強(qiáng)制文件下載而非在瀏覽器打開的自定義函數(shù)分享
有時(shí)我們希望如圖片、文本文檔、網(wǎng)頁(yè)、mp3、pdf等內(nèi)容,當(dāng)點(diǎn)擊對(duì)應(yīng)鏈接時(shí)直接下載,而不是在網(wǎng)頁(yè)上顯示,那么就需要強(qiáng)制設(shè)置header頭信息。以下為一段不會(huì)產(chǎn)生亂碼的php函數(shù)實(shí)現(xiàn)代碼,其他程序語(yǔ)言也可參考之編寫實(shí)現(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基于ip2long實(shí)現(xiàn)IP轉(zhuǎn)換整形
這篇文章主要介紹了PHP基于ip2long實(shí)現(xiàn)IP轉(zhuǎn)換整形,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12PHP使用fopen與file_get_contents讀取文件實(shí)例分享
這篇文章主要介紹了PHP使用fopen與file_get_contents讀取文件實(shí)例分享的相關(guān)資料,需要的朋友可以參考下2016-03-03PHP中遍歷二維數(shù)組_以不同形式的輸出操作實(shí)例
下面小編就為大家?guī)?lái)一篇PHP中遍歷二維數(shù)組_以不同形式的輸出操作實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Laravel框架實(shí)現(xiàn)調(diào)用百度翻譯API功能示例
這篇文章主要介紹了Laravel框架實(shí)現(xiàn)調(diào)用百度翻譯API功能,結(jié)合實(shí)例形式分析了基于Laravel框架的百度翻譯API調(diào)用相關(guān)操作技巧,需要的朋友可以參考下2019-05-05解決windows上php xdebug 無(wú)法調(diào)試的問(wèn)題
這篇文章主要介紹了解決windows上php xdebug 無(wú)法調(diào)試的問(wèn)題,本文分步驟給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02Laravel Memcached緩存驅(qū)動(dòng)的配置與應(yīng)用方法分析
這篇文章主要介紹了Laravel Memcached緩存驅(qū)動(dòng)的配置與應(yīng)用方法,結(jié)合實(shí)例形式分析了在Laravel框架配置Memcached緩存及相關(guān)使用方法,需要的朋友可以參考下2016-10-10