在PHP 中強制下載文件
要為PHP 中的文件提供下載鏈接,您可以使用以下步驟:
檢索文件信息:
<code class="php">$filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); } else { die('The provided file path is not valid.'); }</code>
輸出標頭:
<code class="php">header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName);</code>
輸出檔:
<code class="php">readfile ($filePath); exit();</code>
注意:在函數中實現此操作時要允許此運算下載任意文件,因為您需要防止目錄遍歷並將下載限製到定義的區域。
以上是如何在 PHP 中強制下載檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!