164

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 be able to select a series of images, 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? Thanks!

stalepretzel
  • 14,150
  • 19
  • 71
  • 88

9 Answers9

204

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.

Mark E. Haase
  • 23,180
  • 7
  • 58
  • 69
  • 9
    does it pass w3c validation, or should it be `multiple="multiple"`? – vol7ron Jun 04 '12 at 18:59
  • 10
    I believe it's valid: http://thoughtresults.com/html5-boolean-attributes. It passes the w3c validator if you add . – Mark E. Haase Jun 05 '12 at 00:14
  • 2
    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. – vol7ron Jun 05 '12 at 03:31
  • 11
    It didn't work without adding the property **name** (e.g. `name="file[]"` ). I attempted to [edit the answer](http://stackoverflow.com/review/suggested-edits/4446753), but it got rejected. – Michel Ayres Mar 28 '14 at 12:58
  • 1
    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. – Mark E. Haase Mar 07 '15 at 17:26
  • 1
    How we can restrict user to select only three files while uploading using shift or control button? – CodeGuy Feb 23 '16 at 07:03
96

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!

posit labs
  • 7,733
  • 4
  • 32
  • 57
Epoxys
  • 961
  • 6
  • 2
  • 5
    Thanks for the tip! it saved me so much time +1 – BPm Jun 02 '12 at 23:30
  • 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. – Tariq M Nasim Jan 18 '13 at 06:56
  • 4
    Or you can loop through the files with a `foreach` statement, without having to know the number of files uploaded... – ygesher Nov 10 '13 at 22:32
  • 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. – MyStream Oct 26 '17 at 21:15
8

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>
newfurniturey
  • 34,078
  • 9
  • 85
  • 99
Thaps
  • 111
  • 1
  • 7
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/

MitMaro
  • 5,049
  • 6
  • 28
  • 51
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

2
<form action="" method="POST" enctype="multipart/form-data">
  Select image to upload:
  <input type="file"   name="file[]" multiple/>
  <input type="submit" name="submit" value="Upload Image" />
</form>

Using FOR Loop

<?php    
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    for ($x = 0; $x < count($_FILES['file']['name']); $x++) {               

      $file_name   = $_FILES['file']['name'][$x];
      $file_tmp    = $_FILES['file']['tmp_name'][$x];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }    
?>

Using FOREACH Loop

<?php
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    foreach ($_FILES['file']['name'] as $key => $value) {                   

      $file_name   = $_FILES['file']['name'][$key];
      $file_tmp    = $_FILES['file']['tmp_name'][$key];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }
?>
antelove
  • 2,039
  • 16
  • 14
1

If you use multiple input fields you can set name="file[]" (or any other name). That will put them in an array when you upload them ($_FILES['file'] = array ({file_array},{file_array]..))

Torandi
  • 1,605
  • 2
  • 9
  • 12
0

i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.

$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database

database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like

$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);

and then pass that field into function $fields

$table is the name of the table in which you want to store the data..

function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
    //extracting extension of uploaded file
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $arrayimage["name"]);
    $extension = end($temp);

    //validating image
    if ((($arrayimage["type"] == "image/gif")
    || ($arrayimage["type"] == "image/jpeg")
    || ($arrayimage["type"] == "image/jpg")
    || ($arrayimage["type"] == "image/pjpeg")
    || ($arrayimage["type"] == "image/x-png")
    || ($arrayimage["type"] == "image/png"))

    //check image size

    && ($arrayimage["size"] < 20000000)

    //check iamge extension in above created extension array
    && in_array($extension, $allowedExts)) 
    {
        if ($arrayimage["error"] > 0) 
        {
            echo "Error: " . $arrayimage["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $arrayimage["name"] . "<br>";
            echo "Type: " . $arrayimage["type"] . "<br>";
            echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
            echo "Stored in: ".$arrayimage['tmp_name']."<br>";

            //check if file is exist in folder of not
            if (file_exists($dir."/".$arrayimage["name"])) 
            {
                echo $arrayimage['name'] . " already exists. ";
            } 
            else 
            {
                //extracting database fields and value
                foreach($fields as $key=>$val)
                {
                    $f[]=$key;
                    $v[]=$val;
                    $fi=implode(",",$f);
                    $value=implode("','",$v);
                }
                //dynamic sql for inserting data into any table
                $sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
                //echo $sql;
                $imginsquery=mysql_query($sql);
                move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
                echo "<br> Stored in: " .$dir ."/ Folder <br>";

            }
        }
    } 
    //if file not match with extension
    else 
    {
        echo "Invalid file";
    }
}
//function imageUpload ends here
}

//imageFunctions class ends here

you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

Prateik Darji
  • 2,154
  • 1
  • 9
  • 27
  • 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 – Kunbi Jan 14 '15 at 11:37
-1

partial answer: pear HTTP_UPLOAD can be usefull http://pear.php.net/manual/en/package.http.http-upload.examples.php

there is a full example for multiple files

damko
  • 291
  • 1
  • 12
  • 1
    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. :) – MitMaro Jul 24 '09 at 01:22
  • 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) – damko Jul 24 '09 at 12:37