Download Remote File with PHP to Server and finally output to browser

Shown below is the code to download a remote file with PHP and save to the server and finally output to browser using cURL and readfile

set_time_limit(0);

$url = 'http://example.com/example.zip';
$file = basename($url);

$fp = fopen($file, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

 

Limitations:

  1. Since the file is downloaded to the server first before outputting to the browser, it consumes time, bandwidth & server space.
  2. When downloading large files, the script may exhaust the memory limit and is prone to timeout.

4 Responses

  1. aallisfreehere.blogspot.com November 10, 2013 / 7:50 PM

    Well this is a good think, its not downloading the whole parts so i don’t need much space for serer , i can hotlink them, that’s way i can host 1tb and hot link via a 10gb vps.
    Awesome.
    But the problem is file is saving by “filename.zip” in this case .
    Can you help me by that?

    Thanks in advance.
    aallisfreehere.blogspot.com

    • Mithun John Jacob November 11, 2013 / 12:06 PM

      You can change the Line 4 to $file = "your-filename.zip";

      In the current code, it just saves the file using filename in the file URL.

  2. Fauzi April 2, 2014 / 6:28 PM

    Great!!
    Thanks for Sharing

  3. vikram October 23, 2018 / 5:09 PM

    Wow, This is really helpful for me.
    Thanks a lot.

Leave a Reply

Your email address will not be published. Required fields are marked *