php強制文件下載而非在瀏覽器打開的自定義函數(shù)分享
有時我們希望如圖片、文本文檔、網(wǎng)頁、mp3、pdf等內(nèi)容,當點擊對應(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基于ip2long實現(xiàn)IP轉(zhuǎn)換整形
這篇文章主要介紹了PHP基于ip2long實現(xiàn)IP轉(zhuǎn)換整形,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12PHP使用fopen與file_get_contents讀取文件實例分享
這篇文章主要介紹了PHP使用fopen與file_get_contents讀取文件實例分享的相關(guān)資料,需要的朋友可以參考下2016-03-03Laravel框架實現(xiàn)調(diào)用百度翻譯API功能示例
這篇文章主要介紹了Laravel框架實現(xiàn)調(diào)用百度翻譯API功能,結(jié)合實例形式分析了基于Laravel框架的百度翻譯API調(diào)用相關(guān)操作技巧,需要的朋友可以參考下2019-05-05解決windows上php xdebug 無法調(diào)試的問題
這篇文章主要介紹了解決windows上php xdebug 無法調(diào)試的問題,本文分步驟給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02Laravel Memcached緩存驅(qū)動的配置與應(yīng)用方法分析
這篇文章主要介紹了Laravel Memcached緩存驅(qū)動的配置與應(yīng)用方法,結(jié)合實例形式分析了在Laravel框架配置Memcached緩存及相關(guān)使用方法,需要的朋友可以參考下2016-10-10