簡體   English   中英

要求用戶使用PHP下載文件

[英]Asking user to download file in PHP

我試圖讓瀏覽器提示用戶下載文件。 但是,在嘗試了堆棧溢出和Internet周圍的幾種方法后,由於某種原因,所有方法都以靜默方式失敗。 是否在現代瀏覽器中無法做到這一點?

我只是希望用戶從服務器下載文本(.txt)文件。 我已經嘗試了以下(和更多)此代碼,但無濟於事:

header('Content-disposition: attachment; filename=newfile.txt');
header('Content-type: text/plain');
readfile('newfile.txt');

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".txt";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

我已經嘗試了PHP.NET的示例(沒有一個對我有用): http ://php.net/manual/en/function.readfile.php

我設置了正確的權限,該文件存在且is_可讀。 我現在不知道為什么這樣做不起作用。 任何幫助都會很棒。

我為您提供一種解決方案。

假設download.php是下載文件的文件。

因此,當用戶單擊下載鏈接以顯示確認對話框時,如果用戶選擇是,則將用戶重定向到download.php ,否則下載將不會發生,例如chrome這樣的瀏覽器會在不詢問用戶是否喜歡下載的情況下啟動下載一個文件與否。

暫無
暫無

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

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