I am trying to get a foreach loop to give me the checkbox values (which have the file names for values) from my form, to be added to a zip file.
<input type="checkbox" name="download[0]" value="Fact_Sheet_1.pdf" />
<input type="checkbox" name="download[1]" value="Fact_Sheet_2.pdf" />
<input type="checkbox" name="download[2]" value="Fact_Sheet_3.pdf" />
<input type="checkbox" name="download[3]" value="Fact_Sheet_4.pdf" />
<input type="checkbox" name="download[4]" value="Fact_Sheet_5.pdf" />
Works fine if I click on one checkbox but when I tick more than one checkbox only one file gets added to the zip file.
My code is below. Any suggestions would be appreciated.
if(isset($_POST['submit']) )
{
foreach ($_POST['download'] as $key => $val) {
$filename = 'Fact_Sheets/' . $val;
}
}
system("zip -r files/zipfile $filename");
You overwrite
$filenameeach time.Instead, build it up:
(Also note that it’s conventional to name the
inputs like"download[]", so that the indexing is done automatically for you. This is not crucial, though.)But don’t do this. As discussed in comments, it has a GAPING FLAW. Don’t write this code, even if you’re “just testing”, or even if you’ll “fix it later”. Don’t let it ever exist in the first place, or you will make a mistake, or accidentally leave it in place, or not find the time to do it properly.
I considered not encouraging you by not writing this answer, but concluded that if I allowed some other answer to be accepted, it might be a dangerous answer that’d make things even worse.