1. 程式人生 > >php後端強制前端下載檔案

php後端強制前端下載檔案

點選一個<a>標籤後下載一個檔案

  /**
     * 輸出檔案流
     * @param $filePath  檔案位置
     * @param null $downloadFileName 下載後顯示的檔名
     */
    private function download_file($filePath, $downloadFileName = null) {
        if (file_exists($filePath)) {
            $downloadFileName = $downloadFileName !== null ? $downloadFileName : basename($filePath);
            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($filePath));

            ob_clean();//清空php的緩衝區
            flush();//清空web伺服器的快取區php的緩衝區超過限制php指令碼還沒有結束就會輸出到伺服器的快取區或者瀏覽器的緩衝區  清除他?
            readfile($filePath);
            exit;
        }else{
            redirect($_SERVER['HTTP_REFERER']);//看業務邏輯  這裡是如果檔案不存在  避免調到空白頁面
        }

    }