How to Upload Multiple Files in PHP

The method to upload multiple files in PHP is almost similar to uploading a single file.

If you do not know how to upload a file in PHP, go to this link
How to Upload File in PHP

The differences between uploading multiple files and single file are described in the following points –

  • input tag
    1. The name field is changed to accustom an array which will hold the file names that are uploaded.
    2. The keyword multiple is added to the tag.

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

    As you can see here, uploads is an array and we have used the keyword multiple inside the tag to denote multiple files being uploaded.

  • $_FILES['uploads']['name'][$i] is the way the ith file in the array is referred to. So to get the name the first file, we use $_FILES['uploads']['name'][0], for second file, we use $_FILES['uploads']['name'][1] and so on.

In the code below, there are two files – index.php where multiple files are uploaded and upload.php where the files are moved to destination folder and uploaded files shown to the user.

index.php – Upload Files

<form action="upload.php" method="post" enctype="multipart/form-data">

    <label>Upload image (jpg, jpeg and png extensions only)</label> 
    <input name="uploads[]" type="file" size="30" multiple required /><br><span>(Max size of 1 file : 100Kb)</span><br><br>

    <input name="submit" type="submit" id="submit" class="submit" value="Submit" />

</form>

upload.php – Getting Multiple Files and Moving to Target Directory

<?php

    if(isset($_FILES['uploads']['name'])){

        //Getting the total number of files
        $count = count($_FILES['uploads']['name']); 
        if(!$count){
            echo "Upload files.";
        }
        else{

            // Processing each file iteratively 
            for($i=0;$i<$count;$i++){

                $file_name = $_FILES['uploads']['name'][$i];
                $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                        //Uploading the file
                        $tmp = $_FILES['uploads']['tmp_name'][$i];  
                        $target_dir = "Your target directory/files/";
                        $target_file = $target_dir.basename($file_name);

                        if (move_uploaded_file($tmp, $target_file)){
                            echo '<a href="files/'.$file_name.'" target="_blank">Click here</a> to view the uploaded file.';
                        } 
                        else {
                            echo "Sorry, there was an error uploading your file";
                        }

            }

        }

    }
?>

Index File

Index Page

Uploading The Files

Uploading Files

Uploaded Images

Uploaded Images

Please feel free to download the source code for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No