Upload Multiple Images in PHP with one input

In this post, you’ll learn how to build and upload multiple images in PHP with one input.

If you like to know the very basic of uploading image in PHP you can read on How to upload image with PHP.

Let’s begin with the first simple step.

HTML Form

Just like we did in the previous blog post, we first need to create an HTML Form that will contain the input file field that the users will interact with.

Create a new index.html file in the root directory and add the below code into it.

<form action="imageUpload.php" method="post" enctype="multipart/form-data">
    <label>Upload an Image:</label>
    <input type="file" name="myImages[]" 
           id="imageToUpload" 
           accept="image/png, image/jpeg, image/jpg image/gif"
           multiple required>
    <button type="submit" name="submit">Upload Images Now</button> 
</form>

In the above code, the user will be presented a form with a single input field and an upload button.

This looks similar to the form used in single image tutorial, but with a few add-ons: we added [] to the name attribute of the input field and a multiple attribute.

name = "myImages[]" multiple>

The images[] will contain information for each of the images uploaded in an array. This will allow the server side code to be able to manipulate that information individually. Lastly, the multiple attributes allow for multiple selections of images.

Preview your code on the browser and you’ll see something like this:

Multiple images upload form

Note: Your browsers might display the form field and the button in a different way.

Multiple Images Upload Script

When a user clicks on the file input field, they can select multiple images at once. The imageUpload.php that we specify in the form action attribute will handle the actual upload process.

Create a file imageUpload.php, in the root directory and add this code:

<?php

if ( isset( $_POST['submit'])) {

    $currentDir = getcwd();
    $uploadDir = "/uploads/";

    $errors = []; // Store all errors

    $imageExtensions = ["jpg", "jpeg", "png", "gif"]; // Possible extensions
    
    $images = [];

    $numOfImages = count($_FILES['myImages']['name']); // get the number of images

    for( $i = 0; $i < $numOfImages; $i++) {
        // store each image information
        $images[$i] = [ 
            "name" => $_FILES['myImages']['name'][$i],
            "size" => $_FILES['myImages']['size'][$i],
            "tmp_name" => $_FILES['myImages']['tmp_name'][$i],
            "type"  =>  $_FILES['myImages']['type'][$i]
        ];

        // get the extension
        $imageExtension = strtolower(end(explode( '.' , $images[$i]['name'])));
        
        // check the image extension
        if ( !in_array( $imageExtension, $imageExtensions)) {
            $errors[] = "Atleast one of the images extension is not allowed. Please upload only JPEG, PNG, GIF images<br>";
        }
        // check the image size
        if ( $images[$i]['size'] > 2000000) {
            $errors[] = "Atleast one of the images is more than 2MB. Please only upload images that is equal or less than 2MB<br>";
        }

        // break the loop if error occur
        if ( !empty($errors)) 
            break;
    }

    if ( empty($errors)) {
        // if no errors was found
        $uploaded = false;
        for( $i = 0; $i < sizeof($images); $i++) {
            // upload path
            $uploadPath = $currentDir . $uploadDir . basename($images[$i]['name']);
            // upload the image
            $upload = move_uploaded_file( $images[$i]['tmp_name'], $uploadPath);
            
            // if the image has been uploaded
            if ($upload) {
                $uploaded = true;
            }
        }
        if ( $uploaded) {
            echo $numOfImages . " images where uploaded successfully";
        }
    }
    else {
        foreach( $errors as $error) {
            echo "Something not right: <br>" . $error;
        }
    }
    
}

?>

Let’s explain the code above.

First, we make sure the user click on the submit button:

if ( isset( $_POST['submit'])) {

Next, we get the current working directory and where the images will be stored on the server. So make sure you have a folder with name ‘uploads’ on your root.

$currentDir = getcwd();    
$uploadDir = "/uploads/";

Going forward, we set some variables to collect errors; set the extensions we want; collect the information for each image, and get the total number of images the user try to upload.

$errors = []; // Store all errors

$imageExtensions = ["jpg", "jpeg", "png", "gif"]; // Possible extensions
    
$images = [];

$numOfImages = count($_FILES['myImages']['name']); // get the number of images

Using a for loop, we handle some process:

for( $i = 0; $i < $numOfImages; $i++) {
...
}
  • First, we collectively assign properties of the images uploaded. We assign the name of the image, size, tmp_name, and file type.
  • Next, we get the image extension
  • If the extension is not in our predefined imageExtensions, record an error message.
  • If the image is greater than 2MB, record an error message.
  • Lastly, we try to break the loop, should in case any of the images recorded an error.

Finally, if no error was recorded, each of the images get uploaded, else print out the error message to the user.

Run your code and test with multiple images.

If you’re experience any error with the upload, do not forget to set your PHP.INI constant.

That’s it, we just learnt how to upload multiple images in PHP with one input field.

Leave a Comment

Your email address will not be published. Required fields are marked *