Home > Backend Development > PHP Tutorial > How to Force File Download Using PHP?

How to Force File Download Using PHP?

DDD
Release: 2024-11-23 08:35:22
Original
520 people have browsed it

How to Force File Download Using PHP?

Force File Download using PHP

Background:

You intend to implement a "Download this File" feature on your website to allow users to directly download videos stored on a separate server instead of streaming them in their browsers.

Solution:

To force file download using PHP, you can utilize the following code snippet:

// Specify the file location and remote URL.
$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;

// Set appropriate headers to force download.
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"\"" . $file_name . "\"\"");

// Initiate the download process.
readfile($file_url);
exit; // Prevent any further script output.
Copy after login

Implementation:

  1. Replace $file_name with the name of the video file.
  2. Update $file_url with the actual remote URL of the video file.
  3. Use this code snippet in your PHP script where you want to initiate the download process.

Note: Ensure that fopen_wrappers are enabled to allow readfile to read the remote URL.

The above is the detailed content of How to Force File Download Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template