CBC_NS
CBC_NS

Reputation: 1957

Checking multiple files

I currently have a file element, and a button that allows a user to add more file elements so that if they wanted to, they could select multiple at once. I want to be able to loop through them and need some assistance as to what direction I should take or if there is a correct syntax to do this. Form, php, and JS code below.

Form:

<form action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" method="post" enctype="multipart/form-data" name="upload_form" id="upload_form">
<br />
<input type="file" name="file[]" id="file"/>
<input id="addbutton" type="button" onclick = 'javascript: add()' value="ADD ANOTHER FILE" />
<br />
<input type="submit" id="submit" name="submit" value="SUBMIT" />
</form>

PHP:

if($_POST['submit'] == "SUBMIT")
{
$count = count($_FILES[ "file" ][ "tmp_name" ]);
echo $count;
for($i = 0; $i < $count; ++$i)
{
        if($_FILES && $_FILES['file']['name'])
        {
            //code that does some stuff here
        }
    }
}

JS:

<script>
function add()
{
    var form = document.getElementById("upload_form");
    var addButton = document.getElementById('addbutton');

    var br = document.createElement("br");
    form.insertBefore(br, addButton);

    form = document.getElementById("upload_form");

    input = document.createElement("input");
    input.type="file";
    input.name="file[]";
    form.insertBefore(input, addButton);
}

Upvotes: 0

Views: 68

Answers (2)

Lithilion
Lithilion

Reputation: 1129

Looks perfect, but you can just use this for multiple selection:

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

You won't need that javascript...

Upvotes: 0

karaken
karaken

Reputation: 94

every thing is looks ok, u just need to add index to access particully uploaded file like

   <?php

   // ...
    for($i = 0; $i < $count; ++$i)
    {
        echo $_FILES['file']['tmp_name'][$i];
     // ...

Upvotes: 2

Related Questions