How to Initiate Forced File Downloads in PHP
Forcing file downloads instead of merely linking to them can be crucial in preventing unwanted video playback in browsers. This is especially relevant when video files reside on external servers. Fortunately, PHP provides a solution for this scenario.
To force downloads using PHP, consider the following approach:
1. Configure Headers:
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"". $file_name . "\"");
登入後複製
-
Content-Type: Specifies that the content is an octet stream, which is a binary data stream.
-
Content-Transfer-Encoding: Indicates that the data is transferred in binary format.
-
Content-disposition: Sets the attachment and filename for the download.
2. Call the readfile() Function:
readfile($file_url);
登入後複製
-
readfile() attempts to read the contents of a file and write them to the current output buffer.
-
$file_url is the remote URL where the file is hosted.
3. Prevent Further Output:
- This line ensures that no additional content is output after the download is initiated.
Additional Considerations:
- For readfile() to access the remote URL, ensure that fopen_wrappers is enabled.
- This method initiates the download regardless of the file type. For specific file types, consider using PHP's built-in functions like header('Location: ...') or unlink().
以上是如何在 PHP 中強製檔案下載:確保下載而不是播放?的詳細內容。更多資訊請關注PHP中文網其他相關文章!