Jack Maessen
Jack Maessen

Reputation: 1864

how to count number of uploaded files in php

How can i count the number of uploaded files? This is my form:

<div id="dragAndDropFiles" class="uploadArea">
        <h1>Drop Images Here</h1>
    </div>
    <form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="file" multiple />
        <input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
    </form>

and this is the piece of php which uploads the files:

if($_SERVER['REQUEST_METHOD'] == "POST") {
    $tmpFilePath = $_FILES['file']['tmp_name'];
    $newFilePath = $dir.'/' . $_FILES['file']['name'];
    if(move_uploaded_file($tmpFilePath, $newFilePath)) {
      echo "xxx files are successfully uploaded";
    }
} 

Upvotes: 4

Views: 23096

Answers (6)

Jairo Rodriguez
Jairo Rodriguez

Reputation: 396

You could use the count function:

$no_files = count($_FILES);

Upvotes: 1

Paul Chevalier
Paul Chevalier

Reputation: 1

If no files are selected and your file count is 1, you can use this line before moving the file:

if (!empty($_FILES['file']['tmp_name'][0])) { 
    for($i=0;$i<$countfiles;$i++){

Upvotes: 0

Roberto Marzocchi
Roberto Marzocchi

Reputation: 416

Using the array_filter function it works

try

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

It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.

Upvotes: 3

shotsy247
shotsy247

Reputation: 183

AFriend is correct. The above answers always return 1.

Try:

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

Worked for me anyway.

_t

Upvotes: 10

Asif Uddin
Asif Uddin

Reputation: 409

In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"

  <input type="file" name="file[]" id="file" multiple />

and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.

 <?php echo count($_FILES['file']['name']); ?>

Thanks, i tried in my system get the result.

Upvotes: 13

Nikhil Vaghela
Nikhil Vaghela

Reputation: 2096

Check this answer

<?php echo count($_FILES['file']['name']); ?>

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

Upvotes: 1

Related Questions