I have a page where I am trying to download multiple files with PHP.
If I have the full filepath I can download an individual file like so:
$filepath = '../docs/folder/filename.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush();
readfile($filepath);
exit;
However, I want to be able to get all of the files within a specific folder that have a name in a date range. So my file names all have the same format, that is /folder/ddmmyyxxxx.pdf, and I have a form that gives me the folder and two dates.
$folder = $_POST['doc_type'];
$from_date = $_POST['from_date'];
$to_date = $_POST['to_date'];
$period = new DatePeriod(
new DateTime($from_date),
new DateInterval('P1D'),
new DateTime($to_date)
);
foreach ($period as $date){
$formatted_date = $date->format('dmy');
if(glob('../docs/'.$folder.'/'.$formatted_date.'*.*')){
// download code here
}
}
The download code works with the hard-coded filename but it is not finding any files when I try to loop through the dates even though echoing the $formatted_date and $folder variables gives the start of the file name as expected.
What am I doing wrong or is there a better way of achieving this so that they all download together in a folder rather than looping through them and downloading individually.
Edit
This is what I have now, the var_dump's are showing the correct file path and it will download fine using just one individual file but as it stands now it is just downloading an empty zip folder
$folder = $_POST['doc_type'];
$from_date = $_POST['from_date'];
$to_date = $_POST['to_date'];
$period = new DatePeriod(
new DateTime($from_date),
new DateInterval('P1D'),
new DateTime($to_date)
);
$valid_files = [];
$dir = '../../docs/'.$folder;
$files = scandir($dir);
foreach ($period as $date){
$formatted_date = $date->format('dmy');
foreach($files as $file){
if(strpos($file,$formatted_date)!==false){
$valid_files[] = '../../docs/'.$folder.'/'.$file;
}
}
}
// var_dump($valid_files);
$zipname = 'download.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach($valid_files as $file){
// var_dump($file);
$zip->addFile($file);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($zipname).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zipname));
flush();
readfile($zipname);
exit;