Sasindu H
Sasindu H

Reputation: 1578

PHP file upload count set file

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>";
}
?>

Upvotes: 1

Views: 5506

Answers (4)

Mike
Mike

Reputation: 21

$count_files = 0;
foreach ($_FILES['picture']['error'] as $item) {
    if ($item != 4) {
        $count_files++;
    }
}
echo $count_files;

Upvotes: 2

user188654
user188654

Reputation:

<?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>

Upvotes: 0

sdolgy
sdolgy

Reputation: 7001

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']);

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146430

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

Upvotes: 1

Related Questions