Reputation: 4541
I have a script which lets the users select multiple images while holding CTRL and then upload them to the server. I need to limit the number of selected images to 10, so when the user submits the form, he will get an error if there are more than 10 images.
How would I do this?
P.S: I have a foreach loop that looks like this:
foreach ($_FILES['file']['tmp_name'] as $key => $tmp_name)
A PHP solution would be welcome. Since I do not trust javascript and jquery on this.
EDIT:
This is my script: http://pastebin.com/76NiNB6D
Upvotes: 4
Views: 350
Reputation: 4541
I found the PHP answer I was seeking myself now! :D. What I did is the following:
I checked Carlos's answer and put a variable with a value of 0 outside the loop. Then I created the errors check like Carlos did: if ($file['error'] == 0)
Then I did again what Carlos did inside that IF Statement $number_of_files++;
Now I went outside the loop and did this:
if ($uploaded > 10)
{
unlink($image);
unlink($thumb);
if ($resize) { unlink($res); }
}
This deletes automatically the 11th image, and keeps just 10 images in my server.
Thanks for all the information Carlos, I think I combined it pretty well :P
Upvotes: 0
Reputation: 22972
Your loop is trying to traverse a string. Maybe you meant:
$number_of_files = 0;
foreach ($_FILES as $file)
{
if ($file['error'] == 0)
{
// file uploaded successfully
$number_of_files++;
}
}
if ($number_of_files > 10)
{
die('You uploaded too many files!');
} else {
foreach ($_FILES as $file)
{
if ($file['error'] == 0)
{
copy_the_file_to_destination(); // left as an excercise for the reader ;-)
}
}
}
You could just do count($_FILES);
, but it would count all file inputs, even those that are empty.
Upvotes: 1