Make multiple files to force-download

Sorry if the title doesn't explain much. Let me try to explain further.

I have code that looks like this:

<?
//Grab the number in count.txt
$count = intval(file_get_contents('count.txt'));
//Move the number up one
file_put_contents('count.txt', ++$count);
$number = file_get_contents('count.txt');
//Force Download
header('Content-Disposition: attachment; filename=DataFiles'.$number.".csv");
header('Content-Type: application/octet-stream');

//The data

foreach($array as $info){
echo $info."\n";
}
?>

With $array being an array of data.

Now sometimes the amount of data can be more than 5000, so if the data is over 5000, make another file for every 5000 data that is being echoed. Ea: If there is 20,000 pieces of data in the $array, then it will make a total of 4 files.


Here you are how to download multiple files... The tricks is rendering many iframe in same page. Every frame has different source that force download different files

<?php
for($i = 0; $i<5; $i++){
    echo '<iframe src="test_multiple_downfile.php?text='.$i.'">/iframe>';
}
?>

test_multiple_downfile.php content is this:

$out = $_GET['text'];
header("Content-Type: plain/text");
header("Content-Disposition: Attachment; filename=testfile_".$out.".txt");
header("Pragma: no-cache");
echo "$out";

You cannot send more than 1 file in response to an HTTP request.

What I would suggest is zip the file in a single file and return that.

See: Download multiple files as a zip-file using php


I use AJAX and jQuery to do it, one way to do it, is to prepare all your files and put them into the session where each files have a unique ID. The the return of the ajax call is a call to a JavaScript with the list of IDs.

The the JavaScript has to create as many hidden IFrame and you have IDs and in each of them, call a PHP to download the parts. That is where you put your download headers. Once you have finish the dump of the bytes, you delete them from the session. Using a unique ID and delete them after download makes sure nobody download twice the same file.

What is nice about ti is that if you refresh the page, since the IFrames were dynamic, they don't try to download another time. And if there are an error, the user won't see them since they are hidden IFrames.

Consequently, if there is a problem with the download, instead of sending the header for download, you can send JavaScript alert or call to top.FunctionName('message'); to send some kind of alert to the user.

I was able to go up to 10 downloads at the same time. But the user will be prompt 10 times too. This is something you have to consider if you don't want to zip them.


No, it's not possible, because the HTTP protocol was designed to send one file per one request.