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">
  <meta charset="UTF-8" />
  <title>Multiple File Ppload with PHP</title>
  <form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  <input type="submit" value="Upload!" />

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


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

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

    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

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

    Thank you

  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.

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

      Best regards, Sem

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

    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.

  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:)

    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.

    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

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


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

    4. hi i am also new in PHP can you help me make upload like this web Upload much image just paste url by per line. Please help me

    5. @admin
      Get this source from

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

  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.

  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.

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

    2. Hmm.. i try it.
      If i upload any file i need to see an loading gif-image like here:

      hope you understand me

    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

  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?

  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!

  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

  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?

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

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

    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')";
      nothing speciel there however you might want to sanatize the data

  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?


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

  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 (
    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
    please help.. I'm a noob with php. :/

    sorry for my bad english, i speak spanish


      here a solution

  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 "";echo $name; echo"
    How do I make it echo the new name instead of the real file name?

    Please help me correct this.

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

  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. :)

  19. This comment has been removed by the author.

  20. You rock... For preview before Upload , Using HTML5

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

  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"

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

  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

  25. Sorry if this is posted twice:

    Thank yo for the tutorial. I am getting this error:
    Warning: move_uploaded_file(uploads/ 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/' 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?

  26. Nice + easy + WORKING

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

  28. Hi, when I try to upload more than 4 files at a strech I am getting the following error

    "Warning: Invalid argument supplied for foreach() in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16"

    "Notice: Undefined index: files in C:\wamp\www\multiple-file-upload-with-php\index.php on line 16"

    What might be the issue?

  29. hello sir;
    am thanksfull to you for providing such information. your all iformation is much valuable for me and i hope in the future you will launch more information. if anyone feel problem please visit all android software contant and data

  30. Hi
    Absolut great script

    But need one function, resize of images, could you please add this Option?
    Thank you

  31. hi,

    The function is good but... $message don't use? no return?
    init $message
    $message = array();

    return ($message)?$message:1;

  32. hello, thank you for the tutorial...
    I was wondering, if I want to save the picture name into database with table contains field : dateupload, image1, image2, image3...

    I'll try to do it, but somethinug goes wrong, it become 3 rows data, not 1 rows data like I want to... Could you help me, Sir?

    I put my code after for each, but I don't know how to store the multiple image name...

    $sql = "insert into PIMAGE (dateupload,image1,image2,image3) values (now(),'$name,'$name','$name')";

  33. thank you for the tutorial...
    but sir how to upload more than 20 images

  34. thanks for sharing. Nice work.
    I want to inform you that Source file link not working on any tutorial.
    Please update source file link.
    Thank you

  35. Hello,

    I would want to know how to make for post my photos uploader, please ?
    Thank' for helping

  36. I keep getting an error that tells me 'files' is an undefined index in my php. I can't figure out why not. I've already tried changing the id in the html file from 'file' to 'files'. Any idea how to fix this?

  37. Hola¡ Como se podrían guardar las imágenes en una BD.

  38. Hello there, would it be possible for you to upload multiple files while resizing them all as well?


Go to top