Home >Backend Development >PHP Tutorial >How to Force File Downloads in PHP: Ensuring Downloads Instead of Playback?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 07:43:02742browse

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().

The above is the detailed content of How to Force File Downloads in PHP: Ensuring Downloads Instead of Playback?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn