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
Release: 2024-11-15 07:43:02
Original
674 people have browsed it

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 . "\"");
Copy after login
  • 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);
Copy after login
  • 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;
Copy after login
  • 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template