Home >Backend Development >PHP Tutorial >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.
Implementation:
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!