Home >Backend Development >PHP Tutorial >How Can I Force a File Download Using PHP?
Enforcing File Downloads with PHP
When navigating to a web page, how can we force a file download using PHP?
Solution:
PHP provides a function called readfile() for this purpose. By configuring the headers and utilizing readfile(), we can trigger downloads.
Implementation:
Configure Headers:
Set the following headers to prompt the download:
header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
Use readfile():
Use readfile() to read the file contents and send them to the browser:
readfile($file_url);
Example:
To download a file named "go.exe" from "http://example.com/go.exe", use the following code:
$file_url = 'http://example.com/go.exe'; header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); readfile($file_url);
Additional Notes:
The above is the detailed content of How Can I Force a File Download Using PHP?. For more information, please follow other related articles on the PHP Chinese website!