In the web application, generally, the file is downloaded from the same server. But sometimes the file needs to be downloaded from the remote server. To download file with PHP, you need to force the browser to download the file. Force download in PHP helps to download files from the server and save them to the local drive.
In the example code snippet, we will show you how to force download file from URL in PHP. You can download any type of file (image, ZIP, video, audio, etc) from the remote server using PHP.
Use the readfile() function with application/x-file-to-save
Content-type header, to download a ZIP file from remote URL using PHP.
// Remote download URL
$remoteURL = 'https://www.example.com/files/project.zip';
// Force download
header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".basename($remoteURL));
ob_end_clean();
readfile($remoteURL);
exit;
Note that: The ob_end_clean() function will help to download a large file from the remote server in PHP.
this function work but the file is downloading in active folder as well downloads folder (i need this in downloads only)
I wish to thank you for this snippet code, it was very helpful.