Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.


Live Demo Download Source

HTML Markup

Take a look at the html markup bellow. We need to add a simple html form with input type file and submit property. We also need to give file input type file name with box breaks like files[] and need to add a property named multiple. Here accept is an optional property that used to allow users to upload only image files.

<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Multiple File Ppload with PHP</title>
</head>
<body>
  <form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  <input type="submit" value="Upload!" />
</form>
</body>
</html>

PHP Script

This php code handles uploaded files and save to the server.

$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
	// Loop $_FILES to exeicute all files
	foreach ($_FILES['files']['name'] as $f => $name) {     
	    if ($_FILES['files']['error'][$f] == 4) {
	        continue; // Skip file if any error found
	    }	       
	    if ($_FILES['files']['error'][$f] == 0) {	           
	        if ($_FILES['files']['size'][$f] > $max_file_size) {
	            $message[] = "$name is too large!.";
	            continue; // Skip large files
	        }
			elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
				$message[] = "$name is not a valid format";
				continue; // Skip invalid file formats
			}
	        else{ // No error found! Move uploaded files 
	            if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
	            $count++; // Number of successfully uploaded file
	        }
	    }
	}
}

54 comments:

  1. Anyone know why it would be saving some sort of array file instead of the actual files?

    ReplyDelete
    Replies
    1. Change max_file_uploads value on you php.ini file. By Default it is 20. You can increase as much as you want.

      Delete
    2. but where is the php.ini file anyway? I don't understand how to control the file size as well. please help. thank you

      Delete
  2. Best code on the web!!
    Straight to the point

    Thank you

    ReplyDelete
  3. this code is uploading files in a folder, but i want to upload files in mysql database and then fetch those files with particular ID.

    ReplyDelete
    Replies
    1. Have you found an answer to your question yet? Because I'm also looking for this kind of code...

      Best regards, Sem

      Delete
    2. save the link to file in database table. You can not save files to database.

      Delete
    3. Actually that is not correct "Anonymous"
      Try to take a look at the BLOB fields
      heres a little list of how much data the different types can keep.
      TINYBLOB - 255 bytes
      BLOB - 65535 bytes
      MEDIUMBLOB - 16,777,215 bytes (2^24 - 1)
      LONGBLOB - 4G bytes (2^32 – 1)

      they store data binary lets take a little example while we are at it.

      $saveImage = file_get_contents('/path/to/image/image.jpg');
      mysql_query('INSERT INTO images (picture) VALUES ("' . mysql_real_escape_string($saveImage) . '")');

      The rest is up to you, however it is a slow process if you compare it just uploading it to your webserver
      and storing the link in the database.

      Delete
  4. Thanks a lot. Is it possible to automaticly rename the files, because files from different users may have the same names? (sorry for my bad english, i'm french speaking:)

    ReplyDelete
    Replies
    1. Yap! You can save your files with unique file name with uinqid().
      // get original extension
      $ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
      // create new unique file name with extension
      $uniq_name = uniqid() . '.' .$ext;

      You can also take a look at this example's php section.

      Delete
    2. $ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
      $uniq_name = uniqid() . '.' .$ext;

      i am new to php.
      please tell me where to add the above php code to get unique name. also i want to add the unique number with the php original file name. please send me the script to muthubalaji90@gmail.com

      Delete
    3. Replace this line:
      move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name);

      to:

      $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
      $uniq_name = uniqid() . '.' .$ext;
      move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $uniq_name);

      Delete
    4. hi i am also new in PHP can you help me make upload like this web http://postimage.org/index.php?um=web. Upload much image just paste url by per line. Please help me

      Delete
    5. @admin
      Get this source from http://www.w3bees.com/2013/09/download-file-from-remote-server-with.html

      // explode all lines
      $lines = explode("\n", $data);
      foreach ($lines as $line) {
      download($line);
      }

      Delete
  5. hi...
    good example.But, i want to ask how to upload multiple file to ftp?as your answer above we can use property "multiple" in the form.But,i don't know to do the looping process and where i have to put the "ftp_put" parameter....
    Hope you can help me with full example of coding.

    ReplyDelete
  6. Hello,
    thank you very much for this script.
    It works fine but is this possible to make simple a loading image for upload.
    i think its easyer to see for users.

    sorry for my bat english i'm german.

    ReplyDelete
    Replies
    1. Sorry I do not get you! What do you mean? preview before upload or else? Please clearly...

      Delete
    2. Hmm.. i try it.
      If i upload any file i need to see an loading gif-image like here: http://www.sky-tours.com/images/loading.gif

      hope you understand me

      Delete
    3. For better understanding.
      I mean - File Upload with only one progress bar or animate gif image like in my post below

      Best regards Wolfgang

      Delete
  7. HI! I'm Gianluca from Italy! Great Resalat Haque, how can we load directory - sub_directory and file tree in the same order and save routes in mysql We found webkitdirectory HTML5, but does not load entire folder structure ...? only files and not recursively ... We searched all over the web, but ... nothing ... can you help us?

    ReplyDelete
  8. Hi guy!

    Very good example, easy, fast and completely useful!

    I have modified to save files in random folders and I have added other script as well, to compress in one zip file, you know trying to make a simple we-transfer for local use.

    But, could you give me any tip to make your script valid to uploads files from different folders?

    I have done it showing various lines to select files, but you knnow, it's quite 'dirty'...

    What I'm looking for is that only when I have added some files, only then, show another line/button to add more files.

    Later I will try to discover how to show a progress bar...

    Anyway, many many thanks!!!! I really appreciate your work, THANK YOU!

    ReplyDelete
  9. what framework did you use? is it CodeIgniter? and what type of database storage did you use? can I use wamp or oracle? pls. reply... i just badly need it... btw I'm just a student and I'm hoping that you can really help me with this. because it is part of my requirements as my project to graduate. :) thank you and God Bless

    ReplyDelete
  10. Thanks for your very simple & easy script.
    I've uploaded an image the dimension is 437*656, then re-sized into 460*305. The result was only half of the image is re-sized! What to do to get the full image re-sized?

    ReplyDelete
  11. Hi, im trying to send the file names via email but not sure how to send it any ideas?

    ReplyDelete
  12. Can u please tell me how to insert the file path into mysql database..?

    ReplyDelete
    Replies
    1. As you already know where your storing your data on your webserver
      all you really need to do is make a query to your database with the path information and image name
      $image = "imagename.png"
      $sql = "INSERT INTO DB_NAME (path) VALUES('/path/to/your/$image')";
      mysql_query($sql);
      nothing speciel there however you might want to sanatize the data

      Delete
  13. Hi everyone, this is a very nice script.
    but I keep getting an error when running it:
    Warning: Invalid argument supplied for foreach()

    he gives this error on line "foreach ($_FILES['files']['name'] as $f => $name) {"

    The error only occurs on multiple files, not on a single file.
    Anyone any suggestions?

    thanks

    ReplyDelete
  14. The images gets uploaded but it shows as invalid image when i try to open it.. :(

    ReplyDelete
  15. please, anyone help me. I want to save a path (url of file) on a database, but i cant.
    I modified a little bit the code (http://pastebin.com/KKRw4qfK)
    the files are upload correctly, but only one file is inserted into the database
    that's the code, everytimes i uploads file only first file is inserted into the database
    http://pastebin.com/KKRw4qfK
    please help.. I'm a noob with php. :/

    sorry for my bad english, i speak spanish

    ReplyDelete
    Replies
    1. http://stackoverflow.com/questions/21222356/php-multiple-files-upload-and-gets-path-of-each-ones-files-uploads-for-mysql/21222619?noredirect=1#21222619

      here a solution

      Delete
  16. I am using this script and it works perfect,but i need to echo the url of each uploaded file after it is done .
    I found a way that works ,then I added the code to change the file names. Now I cant get it to echo the new file name just the old one. I added this code

    $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
    $uniq_name = uniqid() . '.' .$ext;
    move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $uniq_name);

    When not changing the name I am able to echo the urls with this
    }
    foreach ($_FILES['files']['name'] as $f => $name)
    {


    echo "http://www.mysite.com/uploader/uploads/";echo $name; echo"
    ";
    }
    How do I make it echo the new name instead of the real file name?



    Please help me correct this.

    ReplyDelete
  17. Thank you very much. Simple and straight foreward.

    ReplyDelete
  18. Sir what code it should be . If I upload a same picture in my folder, I want to have an error pop up to validation. thanks for the answer. :)

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. You rock... For preview before Upload , Using HTML5
    http://www.html5rocks.com/en/tutorials/file/dndfiles/

    ReplyDelete
  21. I'm really appreciate your work, from cambodia web developer.

    ReplyDelete
  22. when i was trying to upload more than 5 files using this code.i am geting an error like this.
    how can i over come this problem .please reply its urgent.....

    "( ! ) Notice: Undefined index: files in ..\addstaff.php on line 55
    Call Stack
    # Time Memory Function Location
    1 0.0007 411576 {main}( ) ..\addstaff.php:0


    ( ! ) Warning: Invalid argument supplied for foreach() in C:\wamp\www\qdoc2\addstaff.php on line 55
    Call Stack
    # Time Memory Function Location
    1 0.0007 411576 {main}( ) ..\addstaff.php:0"

    ReplyDelete
  23. How to add individual image description (title - date - etc) in this case? Thanks.

    ReplyDelete
  24. Hello nice tutorial :D but how can I check the memtype of the file, I already tried with this $_FILES['files']['type'][$f], but it doesn't work.
    For exampla If I hava a .exe file and I change de extension to .jpg the file shouldn't be uploaded, how can I do that?

    And a second doubt :P how can I count the files before the submit and if they are more than the allowed number of images to upload, just upload what it lefts? For example, it's just allowed to upluad 20 images so if I have 15 registered in my database, if I try to upload 10, it only has to upload 5 and the other 5 not

    Thank u :3

    ReplyDelete
  25. Sorry if this is posted twice:

    Thank yo for the tutorial. I am getting this error:
    Warning: move_uploaded_file(uploads/TR0789603194.zip): failed to open stream: No such file or directory in /home5/onlinepc/public_html/action/subs/web_intake.php on line 113

    Warning: move_uploaded_file(): Unable to move '/home5/onlinepc/public_html/tmp/phpUU8kdx' to 'uploads/TR0789603194.zip' in /home5/onlinepc/public_html/action/subs/web_intake.php on line 113

    Line 113 is:
    if(move_uploaded_file($_FILES["text_content"]["tmp_name"][$f], $path.$name))

    My Path is:
    $path = "uploads/";
    Also, How can I save each file path in the database to allow easy download on backend?

    ReplyDelete
  26. Nice + easy + WORKING
    #ThankYouVeryMuch

    ReplyDelete
  27. http://odesktestanswerbd2014.blogspot.com/

    ReplyDelete
  28. how to upload selected folder on sever by drop down menu
    get me idea

    ReplyDelete

Go to top