7

How to Upload Multiple Files & Images in PHP 7 with MySql Example

 2 years ago
source link: https://www.laravelcode.com/post/how-to-upload-multiple-files-images-in-php-7-with-mysql-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Upload Multiple Files & Images in PHP 7 with MySql Example

  10982 views

  2 years ago

PHP

In this tutorial, we will learn how to upload single or multiple files or images in PHP 7 and how to save the images in MySQL database. We will also cover the necessary file uploading validation using the PHP 7 methods and API.

Usually, a user tends to upload a single image and store the image on the database using the file name. This way, we can also fetch the image or file from the database using the file name. Sometimes, based on some specific requirements, we have to upload Multiple images or files on the server.

Tutorial Objective

By the end of this tutorial, you will be able to understand the following concepts:

  • Create an HTML form to select multiple images and files.
  • Display multiple images preview before sending to server.
  • Implement necessary validation before uploading.
  • Save files in the local directory and store the uploaded file path in the database.

Project Files Structure

We are following the given below files and folder structure to upload multiple files in PHP 7.

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

Table Configuration in Database

You can use MAMP or XAMPP to create database and table for multiple file uploading in PHP.

Create database `database_name`.

Create `table_name` inside the database.

Run the following SQL script from the PHPMyAdmin panel to create user tables, and 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 make the connection between the database and PHP project, we defined the database connection with the PDO approach and kept the db 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 a simple file upload form using HTML form tag, the form tag must contain the method=”post” and enctype=”multipart/form-data” tags.

To make it interact with PHP APIs, do define the name=”fileUpload[]” tag with an input form field. By default, the HTML file field allows a single file to upload. Pass the multiple tag with a file input field to choose multiple files at once.

<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

A user must know which files he is going to put on the server, create a html div inside the files upload form.

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

We need to place the jQuery link in the footer and also place the following JavaScript code that shows the 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 7 with Validation

We define the multiple file uploading code in the file-upload.php file and alert the user about 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."
            );
        }
    } 
?>

Add the database connection file to run the SQL query to make the interaction with the database.

Add the validation to make sure whether the images are selected, and the correct file type is chosen, and using the SQL script, insert the files into the database.

If files pass the above validation, then move all the files in the uploads directory with the help of the move_uploaded_file() method and store the images’ location path in the database.

Next, include the file-upload.php file in the form template. It allows users to select the multiple files using PHP 7 and MySQL.

<?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 7 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 7</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>

i hope you like this article.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK