How to Force File Downloads in PHP: Handling Remote Files?

DDD
Release: 2024-11-14 13:48:02
Original
224 people have browsed it

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;
Copy after login

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!

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