check if at least one file was uploaded php
I have a form uploading multiple files:
<?php
$num_uploads = 3;
$num = 0;
while($num < $num_uploads)
{
echo '<div><input name="userfile[]" type="file" /></div>';
$num++;
}
?>
How do I check if at least one file was submitted wit开发者_开发百科h PHP or JavaScript?
Given how you're building the form, you'll have to account for a quirk in how PHP builds the files array.
foreach($_FILES['userfile']['error'] as $key => $err) {
if ($err === UPLOAD_ERR_OK) {
... got at least one file ...
}
}
For some moronic reason, instead of storing each file's upload data in its own seperate sub-array within $_FILES
, PHP opts to instead spread each seperate error/name/tmp_name/etc... across the regular categories like so:
$_FILES = array(
'userfile' => array(
'name' => array(
0 => 'name of file #1'
1 => "name of file #2'
etc...
),
'tmp_name' => array(
0 => 'temp name of file #1'
1 => 'temp name of file #2'
etc.. etc... etc..
)
);
A much more reasonable and understandable version would've been
$_FILES = array(
'userfile' => array(
0 => array(
'name' => 'name of file #1'
'tmp_name' => 'temp name of file #1'
...
),
1 => array(
'name' => 'name of file #2'
'tmp_name' => 'temp name of file #2'
...
but, alas, PHP has yet again saddled the world with an overly convoluted and cumbersome stupidity.
<?php
if (count($_FILES)) {
// at least 1 file
}
?>
Try this,
$i = 0;
foreach ($_FILES as $file){
if($file['size'] > 0){
$i++;
}
}
now if the $i > 0
at least one file is uploaded. $i
is the total numbers of file uploaded.
精彩评论