How to Force Download File from Remote Server in PHP

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.

2 Comments

  1. Shubham Singh Said...
  2. Milton Lima Said...

Leave a reply

keyboard_double_arrow_up