Forcing File Downloads in PHP When Hosted on a Separate Server
When providing users with a "Download this file" option, particularly for videos, it's essential to force the download to prevent in-browser playback. Here's how you can achieve this in PHP even if the video files are stored on a different server:
<?php // Set file details. $file_name = 'file.avi'; $file_url = 'http://www.myremoteserver.com/' . $file_name; // Configure download headers. header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"\"" . $file_name . "\"\""); // Initiate download. readfile($file_url); // Prevent further script output. exit;
This PHP script configures the necessary headers to force the browser to download the file instead of playing it in-browser. It also uses the readfile() function to retrieve and output the file from the remote server.
Note: To enable readfile() to read from a remote URL, ensure that fopen_wrappers is enabled.
The above is the detailed content of How to Force File Downloads in PHP When Hosted on a Separate Server?. For more information, please follow other related articles on the PHP Chinese website!