Home >Backend Development >PHP Tutorial >How to Force File Downloads in PHP: Handling Remote Files?
Forcing File Downloads in PHP: Handling Remote Files
Forcing file downloads instead of opening them in-browser can be crucial for media files. To handle this scenario, where videos reside on a separate server, PHP offers a solution that involves manipulating HTTP headers.
// Locate the file. $file_name = 'file.avi'; $file_url = 'http://www.myremoteserver.com/' . $file_name; // Configure HTTP headers for forced 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); // Terminate the script to prevent any further output. exit;
By setting the Content-Type as application/octet-stream, we indicate that the file is a binary stream for downloading. Content-Transfer-Encoding: Binary ensures that the file's binary format remains intact. Finally, Content-disposition with attachment ensures that the user is prompted to download the file instead of opening it in the browser.
Note that readfile requires fopen_wrappers to be enabled to access files from a remote URL. By utilizing this technique, you can effectively force the download of files stored on a separate server, providing a more user-friendly experience for your website visitors.
The above is the detailed content of How to Force File Downloads in PHP: Handling Remote Files?. For more information, please follow other related articles on the PHP Chinese website!