這篇文章主要介紹了php強制文件下載而非在瀏覽器打開的自定義函數分享,需要的朋友可以參考下。
有時我們希望如圖片、文本文檔、網頁、mp3、pdf等內容,當點擊對應鏈接時直接下載,而不是在網頁上顯示,那么就需要強制設置header頭信息。以下為一段不會產生亂碼的php函數實現代碼,其他程序語言也可參考之編寫實現,代碼如下:
- /**
- * 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;
- }
- }
新聞熱點
疑難解答