Share this:

Learn how to store image files in the MySQL database as well as some necessary file uploading validation in this comprehensive PHP 8 Multiple Files and Images Uploading tutorial.

The most common feature that almost every PHP developer must implement is file upload. As we all know, nearly every web application requires file uploading functionality. A user can’t live without uploading files nowadays, whether it’s on Instagram, Twitter, Facebook, or Tumblr.

We’ll learn how to upload single or multiple files or images in PHP 8 and save them to a MySQL database in this tutorial. We’ll also go over how to use PHP methods and API to perform file upload validation.

In most cases, a user will upload a single image and store it in the database under the file name. We can also use the file name to retrieve an image or file from the database this way. Depending on the situation, we may be required to upload multiple images or files to the server.

Table of Contents

  1. Tutorial Objective
  2. Project Files Structure
  3. Table Configuration in Database
  4. Connect PHP Project with MySQL
  5. Create File Upload Form
  6. Display Multiple Files Preview
  7. Upload Multiple Files in PHP with Validation
  8. Conclusion

Tutorial Objective

  • You should be able to understand the following concepts by the end of this tutorial:
  • To select multiple images and files, create an HTML form.
  • Before sending to the server, show a preview of multiple images.
  • Before uploading, perform the necessary validation.
  • Save files in the local directory and store the uploaded file path in the database.

Project Files Structure

To upload multiple files in PHP 8, we use the files and folder structure listed below.

\-- php-multiple-file-upload
  |-- config
      |--- database.php
  |-- uploads
      |--- image-1
      |--- image-2
      |--- image-3
  |-- file-upload.php
  |-- index.php

Table Configuration in Database

To create a database and table for multiple file uploading in PHP, you can use MAMP or XAMPP.

Create database `database_name`.

Create `table_name` inside the database.

To create user tables, run the following SQL script from the PHPMyAdmin panel. It will have an id, images, and data time values in the MySQL database.

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `images` varchar(255) NOT NULL,
  `date_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Connect PHP Project with MySQL

To connect the database to the PHP project, we used the PDO approach to define the database connection and kept the database configuration in the config/database.php file.

<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=php_crud", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Database connected successfully";
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }
?>

Create File Upload Form with HTML and Bootstrap 4

To create the file upload form we are using Bootstrap 4, add the Bootstrap CDN link in between the head tag.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

Create an HTML form with the method=”post” and enctype=”multipart/form-data” tags to create a simple file upload form.

Define the name=”fileUpload[]” tag with an input form field to make it interact with PHP APIs. The HTML file field allows you to upload a single file by default. To select multiple files at once, use the multiple tag with a file input field.

<form action="" method="post" enctype="multipart/form-data" class="mb-3">
  <div class="custom-file">
    <input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
    <label class="custom-file-label" for="chooseFile">Select file</label>
  </div>
  <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
    Upload Files
  </button>
</form>

Display Multiple Files Preview

Create an html div inside the files upload form if the user knows which files he wants to upload.

<div class="imgGallery">
  <!-- image preview -->
</div>

The jQuery link must be placed in the footer, along with the JavaScript code that displays a preview of all the user-selected files.

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
  $(function () {
    // Multiple images preview with JavaScript
    var multiImgPreview = function (input, imgPreviewPlaceholder) {
      if (input.files) {
        var filesAmount = input.files.length;
        for (i = 0; i < filesAmount; i++) {
          var reader = new FileReader();
          reader.onload = function (event) {
            $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
          }
          reader.readAsDataURL(input.files[i]);
        }
      }
    };
    $('#chooseFile').on('change', function () {
      multiImgPreview(this, 'div.imgGallery');
    });
  });
</script>

Upload Multiple Files in PHP 8 with Validation

In the file-upload.php file, we define the multiple file uploading code and notify the user of the file upload activity.

<?php 
    // Database
    include 'config/database.php'; 
    if(isset($_POST['submit'])){
        
        $uploadsDir = "uploads/";
        $allowedFileType = array('jpg','png','jpeg');
        
        // Velidate if files exist
        if (!empty(array_filter($_FILES['fileUpload']['name']))) {
            
            // Loop through file items
            foreach($_FILES['fileUpload']['name'] as $id=>$val){
                // Get files upload path
                $fileName        = $_FILES['fileUpload']['name'][$id];
                $tempLocation    = $_FILES['fileUpload']['tmp_name'][$id];
                $targetFilePath  = $uploadsDir . $fileName;
                $fileType        = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
                $uploadDate      = date('Y-m-d H:i:s');
                $uploadOk = 1;
                if(in_array($fileType, $allowedFileType)){
                        if(move_uploaded_file($tempLocation, $targetFilePath)){
                            $sqlVal = "('".$fileName."', '".$uploadDate."')";
                        } else {
                            $response = array(
                                "status" => "alert-danger",
                                "message" => "File coud not be uploaded."
                            );
                        }
                    
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "Only .jpg, .jpeg and .png file formats allowed."
                    );
                }
                // Add into MySQL database
                if(!empty($sqlVal)) {
                    $insert = $conn->query("INSERT INTO user (images, date_time) VALUES $sqlVal");
                    if($insert) {
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Files successfully uploaded."
                        );
                    } else {
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error."
                        );
                    }
                }
            }
        } else {
            // Error
            $response = array(
                "status" => "alert-danger",
                "message" => "Please select a file to upload."
            );
        }
    } 
?>

To interact with the database, add the database connection file and run the SQL query.

Add validation to ensure that the images are selected and that the correct file type is selected, then insert the files into the database using the SQL script.

If the files pass the above validation, use the move uploaded file() method to move all of the files in the uploads directory and save the images’ location path in the database.

Then, in the form template, include the file-upload.php file. It uses PHP 8 and MySQL to allow users to select multiple files.

<?php include("file-upload.php"); ?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <title>PHP 8 Upload Multiple Files Example</title>
  <style>
    .container {
      max-width: 450px;
    }
    .imgGallery img {
      padding: 8px;
      max-width: 100px;
    }    
  </style>
</head>
<body>
  <div class="container mt-5">
    <form action="" method="post" enctype="multipart/form-data" class="mb-3">
      <h3 class="text-center mb-5">Upload Multiple Images in PHP 8</h3>
      <div class="user-image mb-3 text-center">
        <div class="imgGallery"> 
          <!-- Image preview -->
        </div>
      </div>
      <div class="custom-file">
        <input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
        <label class="custom-file-label" for="chooseFile">Select file</label>
      </div>
      <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
        Upload Files
      </button>
    </form>
    <!-- Display response messages -->
    <?php if(!empty($response)) {?>
        <div class="alert <?php echo $response["status"]; ?>">
           <?php echo $response["message"]; ?>
        </div>
    <?php }?>
  </div>
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script>
    $(function() {
    // Multiple images preview with JavaScript
    var multiImgPreview = function(input, imgPreviewPlaceholder) {
        if (input.files) {
            var filesAmount = input.files.length;
            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();
                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
                }
                reader.readAsDataURL(input.files[i]);
            }
        }
    };
      $('#chooseFile').on('change', function() {
        multiImgPreview(this, 'div.imgGallery');
      });
    });    
  </script>
  
</body>
</html>

Conclusion

Finally, multiple images Upload in PHP with MySQL Database tutorial is now complete. We learned how to use PHP to add validation to a multiple-file upload component.

I’m assuming you enjoyed this tutorial, and you can find the complete code on GitHub.

Share this:

Categorized in: