Chazy Chaz Chazy Chaz - 4 years ago 102
PHP Question

count($_FILES['file']['tmp_name']) counts the inputs instead of uploaded files

I have many file inputs and I'd like to check how many files are being uploaded at once:

<form id="propForm" class="option" name="imform" action="<?php echo $action[$option]; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="file[]" accept="image/jpeg" />
<input value="<?php echo $op[$option]; ?>" type="submit" name="submitIT">
</form>


In the php file I check it using
count()
:

$file_count = count($_FILES['file']['tmp_name']);

if ( $file_count > 0 && isset($_POST['submitIT']) ) {
echo $file_count;
} else header('Location: /');


If I submit without uploading files, the echo prints 6 (the number of inputs).

How is this possible?

Edit:
$_FILE
content:

Array (
[file] => Array (
[name] => Array (
[0] =>
)
[type] => Array (
[0] =>
)
[tmp_name] => Array (
[0] =>
)
[error] => Array (
[0] => 4
[1] => 4
[2] => 4
[3] => 4
[4] => 4
[5] => 4
)
[size] => Array (
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
)
)
)

Answer Source

Yes, thats how works $_FILES when the inputs have the same name with brackets name="file[]". Example, with 3 inputs and only one file selected:

Array
(
    [file] => Array
    (
        [name] => Array
            (
                [0] => 
                [1] => leon-2.jpg
                [2] => 
            )

        [type] => Array
            (
                [0] => 
                [1] => image/jpeg
                [2] => 
            )

        [tmp_name] => Array
            (
                [0] => 
                [1] => C:\xampp\tmp\php447.tmp
                [2] => 
            )

        [error] => Array
            (
                [0] => 4
                [1] => 0
                [2] => 4
            )

        [size] => Array
            (
                [0] => 0
                [1] => 81945
                [2] => 0
            )

        )

    )

You could check how many files have been uploaded with something like this:

$count = 0;
foreach ($_FILES['file']['tmp_name'] as $tmp_name) {
    if (is_uploaded_file($tmp_name)) {
        $count++;
    }
}

if ($count > 0) { 
  // do something... 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download