程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> php強制文件下載而非在浏覽器打開的自定義函數分享

php強制文件下載而非在浏覽器打開的自定義函數分享

編輯: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;
    }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved