0

i'm looking to create a Zip file on the fly, while downloading it. Let me explain: I have some urls (that change every time) that come from remote servers and i would like to create a container for all (zip archive) so they can be downloaded at once, instead of downloading all files singularly.

Here is my code:

$files = array(
    'http://example.com/file1.pdf'=> array('size'=>55050),
    'http://example.com/file2.doc'=> array('size'=>10000),
    'http://example.com/file3.txt'=> array('size'=>5000)
);
$total_size = 0;
foreach($files as $file=>$info){
    $total_size = $total_size+(int)$info['size'];
}

ob_start();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="Test.zip"');
header('Content-Length: '.$total_size);
header("Content-Transfer-Encoding: binary");
header('Content-Encoding: chunked');

foreach($files as $url=>$info){
    while (@ob_end_flush());
    readfile($url);
}

ob_end_flush();
ob_end_clean();
exit;

This will generate (obviously) a corrupted archive... Can anyone help me? Thanks in advance.

mtshare
  • 3
  • 1
  • 3
  • I think if I did this (I'm not saying my way is correct, but I have done this sort of workflow before), I would grab the files, save to disk separately with `fwrite()`, then use the `ZipArchive` class to add all the saved docs to an archive, download the zip file, then `unlink()` the single files. – Rasclatt Feb 13 '15 at 18:57
  • You can take a look at the following answer: http://stackoverflow.com/a/4369173/935996 – Ramy Deeb Feb 13 '15 at 19:01
  • @Rasclatt thanks for the answer! I don't want to download the files and save them on my server and then create the zip because i would like that the user shouldn't wait until the end of this process... – mtshare Feb 13 '15 at 19:10
  • @RamyDeeb thanks for the answer but the example assume to have the file saved locally.... (not the final zip but the files the you will add to it) – mtshare Feb 13 '15 at 19:12
  • If you can absolutely trust the source of the files you can use file_get_contents(), it will read the file and return you a string of the contents, here is the doc and some examples: http://php.net/manual/en/function.file-get-contents.php – Ramy Deeb Feb 13 '15 at 19:18
  • Well the process is, for-all-intensive purposes, instant. To the user it would appear instant. My explanation sounds like it might be a long wait process but the transaction would not be noticeably slower than doing some sort of saving to memory option – Rasclatt Feb 13 '15 at 19:52

0 Answers0