首頁 > 後端開發 > php教程 > 如何在 PHP 中強製檔案下載:確保下載而不是播放?

如何在 PHP 中強製檔案下載:確保下載而不是播放?

Linda Hamilton
發布: 2024-11-15 07:43:02
原創
675 人瀏覽過

How to Force File Downloads in PHP: Ensuring Downloads Instead of Playback?

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:

exit;
登入後複製
  • 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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板