0

I wanna use php to download some zip files from a url. I.E. sitename.com/path/to/file/id/123 when you go to this url directly you get a file download prompt. I've tried to use fopen() and file_get_contents() but these fail. The search I've done comeback with how to make a zip file downloadable or how to get the file from sitename.com/path/to/file.zip but my url doesn't have a .zip extension.

fopen ('url.com') or die('can not open');

The browser shows can not open

Cjueden
  • 1,200
  • 2
  • 13
  • 25
  • 1
    `but these fail.` what message did you get trying these methods? show the code, please. – Cheery Jan 31 '12 at 04:07
  • should probably use `http://url.com` and if it's not dying but not showing try echoing – Moak Jan 31 '12 at 04:12
  • It is not enough. There could be a list of problems. Do you see any output (it will be weird without the right headers) or error message? `echo file_get_contents('http://url.com/file');` – Cheery Jan 31 '12 at 04:12

2 Answers2

5

The url is probably a script that may be redirecting you. Use CURL instead

$fh = fopen('file.zip', 'w');
$ch = curl_init()
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_FILE, $fh); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
curl_exec($ch);
curl_close($ch);
fclose($fh);
James L.
  • 4,032
  • 1
  • 15
  • 15
  • 1
    The zip file is downloading as an empty zip file. Any ideas what could be wrong? – TimNguyenBSM Jun 08 '15 at 01:36
  • This answer doesn't work any more. It only creates an empty ZIP file. – Omar Tariq Dec 02 '15 at 21:27
  • If you get an empty file and on the server the zip works, then you probably need to set a content length. header("Content-Length: " . filesize($yourfile)); – M H Feb 13 '17 at 19:47
  • if someone also has the problem that only a part of the data is downloaded: GIVE MORE TIME! `curl_setopt($ch, CURLOPT_TIMEOUT, (60*30)); // 30 minutes` Also of course allow the script to run as long as it is. – Sarah Trees Mar 19 '20 at 12:10
1

It's probably easier to use the more basic functions like readfile() for this sort of thing.

Adapted from an example at php.net:

<?php
// We'll be outputting a ZIP
header('Content-type: application/zip');

// Use Content-Disposition to force a save dialog.
// The file will be called "downloaded.zip"
header('Content-Disposition: attachment; filename="downloaded.zip"');

// The ZIP source is in original.zip
readfile('original.zip');
?>
ghoti
  • 45,319
  • 8
  • 65
  • 104