簡體   English   中英

在php中強制下載文件

[英]Force file download in php

我已經構建了一個簡單的文件管理器,用戶可以下載任何類型的文件,如pdf,word或gif文件。 我希望他們所有人都下載文件,而不是在瀏覽器中查看它。 上傳的文件名存儲在數據庫中。

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?> 

http://php.net/manual/en/function.header.php

您可以使用“Content-Disposition”標題:

header("Content-Disposition: attachment");

PHP手冊為此提供了一個很好的例子。

通常在發送文件之前將Content-Disposition設置為attachment ,強制瀏覽器下載。

您需要配置Web服務器以為文件提供此標頭,或者通過PHP自己發送它們,然后發送特定標頭,如下所示:

header('Content-Disposition: attachment; filename=your_file_name.pdf');

請注意第一個解決方案更好,因為您不會因為腳本運行時間過長而導致下載風險被削減(您也可以更改它)。

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/pdf;\n");
$len = filesize($filename);
header("Content-Length: $len;\n");
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n");
echo readfile($filename)

源代碼取自TCPDF

            // download PDF as file
            if (ob_get_contents()) {
                $this->Error('Some data has already been output, can\'t send PDF file');
            }
            header('Content-Description: File Transfer');
            if (headers_sent()) {
                $this->Error('Some data has already been output to browser, can\'t send PDF file');
            }
            header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
            header('Pragma: public');
            header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
            // force download dialog
            if (strpos(php_sapi_name(), 'cgi') === false) {
                header('Content-Type: application/force-download');
                header('Content-Type: application/octet-stream', false);
                header('Content-Type: application/download', false);
                header('Content-Type: application/pdf', false);
            } else {
                header('Content-Type: application/pdf');
            }
            // use the Content-Disposition header to supply a recommended filename
            header('Content-Disposition: attachment; filename="'.basename($name).'";');
            header('Content-Transfer-Encoding: binary');
            $this->sendOutputData($this->getBuffer(), $this->bufferlen);
            break;

無論如何最重要的部分是

 header('Content-Disposition: attachment; filename="'.basename($name).'";');

並注意到最后; 在字符串內部,沒有它,它將無法正常工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM