How do i upload multiple images in PHP with Image Preview

Published October 13, 2021

Discover a simple solution for uploading multiple images to your server using PHP, HTML, and Bootstrap 5. Enhance your web applications with this easy-to-follow tutorial

Here's a comprehensive guide on how to achieve this

  • Create Simple HTML form with Bootstrap5 file input
  • Create a JS file to show preview of uploading images
  • Create a PHP file to upload images

 

To upload image we need input type "file" and enctype ="multipart/form-data" on form submission.

Upload multiple images with php server

 

So let's create a Form UI

Create Simple HTML form with Bootstrap5 file input

<html>
  <head>
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
    <script type="text/javascript" src="show.js"></script>
    <style>
      .container {
        max-width: 600px;
      }
      .card{
        float: left;
      }
    </style>
  </head>
  <body>
    <div class="container mt-5">
      <form action="create_photo_gallery.php" method="POST" enctype="multipart/form-data" id="imageInputForm">
        <div class="custom-file">
       
       
          <input type="file" id="uploadImageFile" class="form-control form-control-lg" name="uploadImageFile[]" onchange="showImageHereFunc();" multiple/>
          <label class="custom-file-label" for="chooseFile">Select file</label>
        </div>
        <input type="submit" name="uploadImage" class="btn btn-primary btn-block mt-4" value="Upload"/>
      </form>
      <div class="user-image mb-3 text-center">
        <div id="showImageHere">
          <div class="card-group">
            <div class="row">
              <!-- Image preview -->
            </div>
          </div>    
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

   <script>
   $(document).ready(function() { 
  $('#imageInputForm').ajaxForm(function() {
    alert("Uploaded!");
   }); 
});
function showImageHereFunc() {
  var total_file=document.getElementById("uploadImageFile").files.length;
  for(var i=0;i<total_file;i++) {
    $('#showImageHere').append("<div class='card col-md-4'><img class='card-img-top' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");
  }
}</script>
  </body>
</html>

 

 

Create a JS file to show preview of uploading images

Now we create a javascript file which we will use to preview the image before upload the images

$(document).ready(function() { 
  $('#imageInputForm').ajaxForm(function() {
    alert("Uploaded!");
   }); 
});
function showImageHereFunc() {
  var total_file=document.getElementById("uploadImageFile").files.length;
  for(var i=0;i<total_file;i++) {
    $('#showImageHere').append("<div class='card col-md-4'><img class='card-img-top' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");
  }
}

 

Create a PHP file to upload images

<?php
if(isset($_POST['uploadImage'])) {
  for($i=0;$i<count($_FILES["uploadImageFile"]["name"]);$i++) {
    $uploadfile=$_FILES["uploadImageFile"]["tmp_name"][$i];
    $folder="photo_gallery/";
    move_uploaded_file($_FILES["uploadImageFile"]["tmp_name"][$i], "$folder".$_FILES["uploadImageFile"]["name"][$i]);
  }
  exit();
}
?>

Explanation:

  1. HTML Form:

    • The multiple attribute on the file input allows users to select multiple files.
    • Bootstrap 5 classes are used for styling.
  2. PHP Script:

    • File Validation: Checks if the uploaded files are of allowed formats.
    • Unique Filename Generation: Creates a unique filename to prevent overwriting.
    • File Upload: Uses move_uploaded_file() to move the uploaded file to the target directory.
    • Image Preview: Optionally displays the uploaded image using an img tag with Bootstrap's img-thumbnail class.

Additional Considerations:

  • Error Handling: Implement robust error handling to catch exceptions and display informative messages.
  • Security: Validate file sizes, sanitize filenames, and consider using prepared statements if interacting with a database.
  • Image Optimization: Optimize images for web use to reduce file size and improve loading times.
  • User Experience: Provide visual feedback to the user during the upload process, such as progress bars or notifications.
  • Database Integration: If necessary, store the uploaded file paths or other relevant information in a database.

By following these steps and considering the additional points, you can effectively implement multiple image uploads with preview in your PHP applications using Bootstrap 5