How can I select and upload multiple files with HTML and PHP, using HTTP POST?

363,982

Solution 1

This is possible in HTML5. Example (PHP 5.4):

<!doctype html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="my_file[]" multiple>
            <input type="submit" value="Upload">
        </form>
        <?php
            if (isset($_FILES['my_file'])) {
                $myFile = $_FILES['my_file'];
                $fileCount = count($myFile["name"]);

                for ($i = 0; $i < $fileCount; $i++) {
                    ?>
                        <p>File #<?= $i+1 ?>:</p>
                        <p>
                            Name: <?= $myFile["name"][$i] ?><br>
                            Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
                            Type: <?= $myFile["type"][$i] ?><br>
                            Size: <?= $myFile["size"][$i] ?><br>
                            Error: <?= $myFile["error"][$i] ?><br>
                        </p>
                    <?php
                }
            }
        ?>
    </body>
</html>

Here's what it looks like in Chrome after selecting 2 items in the file dialog:

chrome multiple file select

And here's what it looks like after clicking the "Upload" button.

submitting multiple files to PHP

This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.

Solution 2

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

<form enctype="multipart/form-data" action="post_upload.php" method="POST">

Then the key to success;

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

do NOT forget those brackets! In the post_upload.php try the following:

<?php print_r($_FILES['file']['tmp_name']); ?>

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

$_FILES['file']['tmp_name'][0]

You can use php count() to count the number of files that was selected. Goodluck widdit!

Solution 3

Full solution in Firefox 5:

<html>
<head>
</head>
<body>
 <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
  <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> 
 </form>

<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>"; 


$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {

 echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
 $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 

 // generate a random new file name to avoid name conflict
 $fPath = md5(rand() * time()) . ".$ext";

 echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
 $result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);

 if (strlen($ext) > 0){
  echo "Uploaded ". $fPath ." succefully. <br>";
 }
}
echo "Upload complete.<br>";
?>

</body>
</html>

Solution 4

in the first you should make form like this :

<form method="post" enctype="multipart/form-data" >
   <input type="file" name="file[]" multiple id="file"/>
   <input type="submit" name="ok"  />
</form> 

that is right . now add this code under your form code or on the any page you like

<?php
if(isset($_POST['ok']))
   foreach ($_FILES['file']['name'] as $filename) {
    echo $filename.'<br/>';
}
?>

it's easy... finish

Solution 5

If you want to select multiple files from the file selector dialog that displays when you select browse then you are mostly out of luck. You will need to use a Java applet or something similar (I think there is one that use a small flash file, I will update if I find it). Currently a single file input only allows the selection of a single file.

If you are talking about using multiple file inputs then there shouldn't be much difference from using one. Post some code and I will try to help further.


Update: There is one method to use a single 'browse' button that uses flash. I have never personally used this but I have read a fair amount about it. I think its your best shot.

http://swfupload.org/

Share:
363,982

Related videos on Youtube

stalepretzel
Author by

stalepretzel

I like math, therefore I like computers.

Updated on June 08, 2021

Comments

  • stalepretzel
    stalepretzel almost 3 years

    I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.

    For example, I'd like to select a series of images and then upload them to the server, all at once.

    It would be great to use a single file input control, if possible.

    Does anyone know how to accomplish this?

    • sourcerebels
      sourcerebels almost 15 years
      Hi, It is possible to you to upload a archive file (zip, rar, tar, ...)?
  • MitMaro
    MitMaro almost 15 years
    You can use the PEAR package but this task is fairly trivial and unless you need the extra features that the package provides (internationalized error messages, validation, etc...) I would recommend using the native PHP functions. But this is only my opinion. :)
  • Meep3D
    Meep3D almost 15 years
    I've used swfupload fwiw - it's a bit of a pain on occasions but it's not really that hard to get working.
  • damko
    damko almost 15 years
    I agree with you, that's why I wrote "partial answer". But I also do my best to re-use code and I often work as much as I can with pear (pear coders are much more better than me :-D)
  • Thaps
    Thaps over 12 years
    The code clipped. Here's what comes just above it: <html> <head> </head> <body> <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" > <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> </form>
  • Thaps
    Thaps over 12 years
    It didn't work in IE8 though, but then just use a real browser.
  • BPm
    BPm almost 12 years
    Thanks for the tip! it saved me so much time +1
  • vol7ron
    vol7ron almost 12 years
    does it pass w3c validation, or should it be multiple="multiple"?
  • Wowbagger and his liquid lunch
    Wowbagger and his liquid lunch almost 12 years
    I believe it's valid: thoughtresults.com/html5-boolean-attributes. It passes the w3c validator if you add <!doctype html>.
  • vol7ron
    vol7ron almost 12 years
    yeah, it probably validates HTML, but fails XHTML. Even though I still like to use XHTML, I think people advise to stay away from it these days.
  • MitMaro
    MitMaro almost 12 years
    @Barsoom is correct. Things have gotten much better on the multiple file uploads in the last couple years. :D
  • Tariq M Nasim
    Tariq M Nasim over 11 years
    It works very fine ... but I'm having trouble uploading this way in Internet Explorer (v8). I think IE doesn't support uploading this way.
  • ygesher
    ygesher over 10 years
    Or you can loop through the files with a foreach statement, without having to know the number of files uploaded...
  • Michel Ayres
    Michel Ayres about 10 years
    It didn't work without adding the property name (e.g. name="file[]" ). I attempted to edit the answer, but it got rejected.
  • Kunbi
    Kunbi over 9 years
    Hi all, I use the file input to attach documents to an autogenerated email. I am able to attach multiple documents at a go, however, I would like to attach multiple documents from different directory. Presently if I do this my currently selected document is replace by the new document I select. Please how do I go about this. Thanks
  • Wowbagger and his liquid lunch
    Wowbagger and his liquid lunch about 9 years
    Thanks @MichelAyres, I have updated my answer. When I orginally wrote this, I only addressed the HTML part of the problem b/c there were other answers that explained the PHP part. Over time, this became a popular answer, so I've now expanded to cover both HTML and PHP.
  • Rahul
    Rahul over 8 years
    How we can restrict user to select only three files while uploading using shift or control button?
  • MyStream
    MyStream over 6 years
    Note, if you use a key in your name in your html, e.g. name="file[3]", then you need to access the value via $_FILES['file']['tmp_name'][3], in case that's not obvious.