Norman
Norman

Reputation: 6365

php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array

Ok. I give up on this. When uploading multiple files to the server using php, what is a fail safe method to return the count of files the user has actually uploaded?

Whatever I have done so far, returns the count of all the fields in the form, and the count of the files a user uploads. So if the total fields in the form were 3 and a user uploaded only 2 files, I still get 3 as the count of file uploaded.

One place suggested using array_filter to do this, but that's totally beyond me.

echo count($_FILES['file']['tmp_name']); //3

echo count($_FILES['file']); //3

Any fail safe method you follow and can suggest other than looping through the FILES array size to check for this?

My form is structured like any other:

<form action="process.php" method="post" enctype="multipart/form-data">
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="file" name="file[]"></div>
<div><input type="submit"></div>
</form>

Upvotes: 3

Views: 7388

Answers (3)

arunrc
arunrc

Reputation: 628

Try this

$count = 0;
$fileCount=count($_FILE['file']['name'];)
$fileSize=$_FILES['file']['size'];

    for($i=0;$i<$ fileCount;$i++) {
        if ($fileSize[$i] > 0) {
           $count++;
        }
    }

Upvotes: 0

Rikudou_Sennin
Rikudou_Sennin

Reputation: 1375

Exactly as they told you, just simply use array_filter().

echo count(array_filter($_FILES['file']['name']));

It will return the right number

Upvotes: 9

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

$count = 0;
foreach($_FILES as $file) {
    if(isset($file["file"]["tmp_name"]) && !empty($file["file"]["tmp_name"]))
        $count++;
}

Upvotes: 0

Related Questions