簡體   English   中英

磁盤上的 PHP 輸出文件到瀏覽器

[英]PHP output file on disk to browser

我想在 PHP 中向瀏覽器提供現有文件。 我看過有關 image/jpeg 的示例,但該函數似乎將文件保存到磁盤,您必須先創建一個大小合適的圖像對象(或者我只是不明白它:))

在asp.net 中,我通過讀取字節數組中的文件然后調用context.Response.BinaryWrite(bytearray) 來實現,所以我在PHP 中尋找類似的東西。

米歇爾

fpassthru()應該完全滿足您的需求。 請參閱手冊條目以了解以下示例:

<?php

// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

?>

有關 PHP 的所有文件系統函數,請參見此處

如果它是您想提供下載的二進制文件,您可能還想發送正確的標題,以便彈出“另存為..”對話框。 有關要發送的標頭的一個很好的示例,請參閱此問題的第一個答案。

我用這個

  if (file_exists($file)) {


        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        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($file));

        ob_clean();
        flush();
        readfile($file);
        exit;

    } 

我使用 readfile() ( http://www.php.net/readfile ) ...

但是您必須確保使用 header() 設置正確的“內容類型”,以便瀏覽器知道如何處理該文件。

您還可以強制瀏覽器下載文件,而不是嘗試使用插件來顯示它(例如 PDF),我總是覺得這看起來有點“hacky”,但在上面的鏈接中對此進行了解釋。

這應該讓你開始: http : //de.php.net/manual/en/function.readfile.php

編輯:如果您的網絡服務器支持它,請使用

header('X-Sendfile: ' . $filename);

其中文件名包含本地路徑,如

/var/www/www.example.org/downloads/example.zip

比 readfile() 快。

(使用 header() 的通常安全注意事項適用)

對於我的網站和我為客戶創建的網站,我使用了很久以前發現的 PHP 腳本。

可以在這里找到: http : //www.zubrag.com/scripts/download.php

除了不允許熱鏈接(默認)之外,我使用了它的一個稍微修改過的版本,以允許我混淆文件系統結構(默認情況下),並且我添加了一些額外的跟蹤功能,例如引用者、IP(默認) ,以及我可能需要的其他此類數據。

希望這可以幫助。

以下將啟動 XML 文件輸出

$fp = fopen($file_name, 'rb');

// Set the header
header("Content-Type: text/xml");
header("Content-Length: " . filesize($file_name));
header('Content-Disposition: attachment; filename="'.$file_name.'"');

fpassthru($fp);
exit;

“內容處理:附件”很常見,Facebook 等網站使用它來設置正確的標題

暫無
暫無

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

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