Sometimes, we want to force file download with PHP
In this article, we’ll look at how to force file download with PHP.
How to force file download with PHP?
To force file download with PHP, we can add a few response headers with header
.
For instance, we write
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
to call header
with the Content-disposition
response header set to attachment
.
And we set the filename
response header to the file name we want the download file to have.
We do all this with
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
Then we call readfile
with $file_url
to open the file and force the download of the file because of the headers we added.
Conclusion
To force file download with PHP, we can add a few response headers with header
.