1

I want to count set file upload. Here is my using code. Are there any better method to do this. Thanks.

<form action="index.php" method="post" enctype="multipart/form-data">
    <input name="new_image[]"  type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
<button name="submit" type="submit">Upload</button>
</form>
<?php

$img_error = '0';
$fill_img_count = '0';
if(isset($_POST['submit']))
{
    $img_count = count($_FILES['new_image']);
    echo "Total : ".$img_count."<br>";
    for ($i=0 ; $i<=$img_count ; $i++)
    {
        if (isset($_FILES['new_image']) && !empty($_FILES['new_image']['name'][$i]))
        {
            $fill_img_count++;
        }
    }
    echo "Set : ".$fill_img_count."<br>";
}
?>

4 Answers 4

2
$count_files = 0;
foreach ($_FILES['picture']['error'] as $item) {
    if ($item != 4) {
        $count_files++;
    }
}
echo $count_files;
Sign up to request clarification or add additional context in comments.

Comments

1

I'd recommend testing each ['error'] key against UPLOAD_ERR_OK.

Comments

0

You don't require to have name="new_image[]" as the name ... just new_image will suffice. If you post 1 or many, on the PHP side, you'll see $_FILES[]

Some useful links for you:

Some code:

  if (empty($_FILES)) { echo "0 files uploaded"; } 
  else { echo count($_FILES) . " files uploaded"; }

Edit based on comment:

From that post:

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

1 Comment

This code will fail in case empty file fields are sent which is something OP is explicitly looking to avoid.
0
<?php
$count = 0;
foreach($_FILES['new_image']['error'] as $status){
    if($status === UPLOAD_ERR_OK) {
        $count++;
    }
}
var_dump($count);
?>
<form action="test.php" method="post" enctype="multipart/form-data">
    <input name="new_image[]"  type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
    <input name="new_image[]" type="file" />
<button name="submit" type="submit">Upload</button>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.