8

I am trying to load multiple files using HTML5. This is my code I found on some site. In the PHP code it doesn't recognize it as an array.

Am I doing something wrong? Can someone show me a working solution?

Thanks.

index.html

<form action='save.php' method='post' enctype='multipart/form-data'>
<input name="uploads" type="file" multiple="multiple" />
<input type='submit' value="Upload File">
</form>

save.php

function GetFiles() {
        $files = array();
        $fdata = $_FILES["uploads"];
        if (is_array($fdata["name"])) {//This is the problem
                for ($i = 0; $i < count($fdata['name']); ++$i) {
                        $files[] = array(
                            'name' => $fdata['name'][$i],
                            'tmp_name' => $fdata['tmp_name'][$i],
                        );
                }
        } else {
                $files[] = $fdata;
        }

        foreach ($files as $file) {
                // uploaded location of file is $file['tmp_name']
                // original filename of file is $file['file']
        }
}
1
  • The answers below have correctly solved the problem, and here's a page with a complete working example that might help someone else who stumbles upon this page: tiffanybbrown.com/2011/03/29/… Commented Jul 28, 2011 at 18:54

3 Answers 3

9

You need to make some sort of array of the name:

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

Just like you used to do when using checkboxes.

Sign up to request clarification or add additional context in comments.

Comments

7

form variables that are arrays must be named with a [], otherwise PHP doesn't see it as an array. So:

<form action='save.php' method='post' enctype='multipart/form-data'> 
<input name="uploads[]" type="file" multiple="multiple" /> 
<input type='submit' value="Upload File"> 
</form> 

should do it.

Comments

1

I know this is kind of a old thread but I use this little script to convert the (to me) confusing layout of the $_FILES array to a more readable form. Name_input is whatever name you gave to the Input object in HTML.

for($i=0; $i<count($_FILES['name_input']['name']); $i++) {
    $betterfiles[] = array(
        "name" => $_FILES['name_input']['name'][$i],
        "type" => $_FILES['name_input']['type'][$i],
        "tmp_name" => $_FILES['name_input']['tmp_name'][$i],
        "error" => $_FILES['name_input']['error'][$i],
        "size" => $_FILES['name_input']['size'][$i]
    );
}

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.