How to upload multiple image in PHP

How to upload multiple image in PHP

In this tutorial, we are going to learn "How to upload multiple images in PHP". Image upload is one of the most important requirements of any website or any web application. In this tutorial, I am going to show you step-by-step "how to upload multiple images in PHP".

Image upload in php

Get Source Code

Folder and file structure


Image-upload-in-php

HTML Form

<?php
    ob_start();
    session_start();    
    require_once('../1config/conn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
    <?php
        require_once('../1config/all_css.php');
    ?>
</head>
<body>
    <div class="container mt-5 p-0">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header"><h4>Multiple image upload in php</h4></div>
                    <div class="card-body">
                        <form action="../3management/upload.php" method="post" enctype="multipart/form-data" >
                            <div class="row">
                                <div class="col-lg-12">
                                    <?php
                                        if(isset($_SESSION['success']) && ($_SESSION['success'] != ''))
                                        {
                                            echo "<div class='alert alert-success'>".$_SESSION['success']."</div>";
                                            session_unset();
                                        }
                                        if(isset($_SESSION['error']) && ($_SESSION['error'] != ''))
                                        {
                                            echo "<div class='alert alert-danger'>".$_SESSION['error']."</div>";    
                                            session_unset();
                                        }
                                    ?>
                                </div>
                            </div>
                            <div class="row m-2">
                                <div class="col-lg-6">
                                    <input type="file" name="images[]" id="selectimage" class="form-control" autocomplete="off" placeholder="Enter Your Name" multiple>
                                    <button type="submit" class="mt-3 submitbutton btn btn-primary" name="uploadbutton">SUBMIT</button>
                                </div>
                                <div class="col-lg-6">
                                    <img src="../4assets/product-placeholder.jpg" alt="" width="300px" height="300px" id="imageobject">
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
        require_once('../1config/all_js.php');
    ?>
</body>
</html>

This PHP code represents a web page for uploading multiple images. Let's break down the code step by step:

1. ob_start() and session_start(): These functions are used to start output buffering and session respectively. Output buffering is useful when you want to send headers or set cookies after content has been sent, and sessions are used to store user data across multiple pages.

2. require_once('../1config/conn.php'): This line includes a PHP file named 'conn.php' located in the '../1config/' directory. This file is typically used to establish a database connection.

3. HTML structure: The code contains the standard structure of an HTML page with a head and body section.

4. Inside the head section:
  • It includes meta tags for the character set and viewport settings.
  • It sets the title of the page to "Image Upload".
  • It includes CSS files using require_once('../1config/all_css.php').
5. Inside the body section:
  • A container <div> with Bootstrap classes is used for layout.
  • A form is created with the action set to "../3management/upload.php". This form is used to upload images.
  • The enctype attribute is set to "multipart/form-data" to allow file uploads.
  • There are two file input fields with the name "images[]", allowing multiple file uploads.
  • A submit button with the name "uploadbutton" is included.
6.PHP code:
  • It checks if there is a success or error message stored in the session variables ($_SESSION['success'] and $_SESSION['error']).
  • If there is a success message, it displays it in a green alert box.
  • If there is an error message, it displays it in a red alert box.
  • After displaying the messages, it unsets the session variables to clear them.
7. There's a placeholder image displayed initially. When a user selects an image using the file input field, JavaScript can be used to preview the selected image.
8. At the end of the body section, JavaScript files are included using require_once('../1config/all_js.php').
Image-upload-in-php

Connection Code

<?php
    $hostname = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'php_image';
    $conn = mysqli_connect($hostname, $username, $password, $database);
    if(!$conn)
    {
        die('Not Connected');
    }
?>

1. $hostname, $username, $password, and $database: These variables store the credentials and database information required to connect to the MySQL database. In this case, the script is configured to connect to a MySQL server running on the local machine (localhost) using the username root, an empty password (which is common for local development environments, but not recommended for production), and the database named php_image.

2. $conn = mysqli_connect($hostname, $username, $password, $database);: This line establishes a connection to the MySQL database using the mysqli_connect() function. It takes four parameters: the hostname (or IP address) of the MySQL server, the username to access the database, the password associated with the username, and the name of the database to connect to. The function returns a MySQL connection object ($conn) if the connection is successful, or false if an error occurs.

3. if(!$conn) { die('Not Connected'); }: This conditional statement checks if the connection to the database was unsuccessful. If $conn evaluates to false, it means that the connection attempt failed. In such cases, the script terminates execution with the die() function, which outputs the specified message ('Not Connected') and stops further script execution. This message indicates that the script was unable to establish a connection to the database.
Image upload in php

PHP code for file upload

<?php
    ob_start();
    session_start();
    require_once('../1config/conn.php');
    if(isset($_POST['uploadbutton'])) {
        $imageNames = $_FILES['images']['name'];
        $imageTempNames = $_FILES['images']['tmp_name'];
        $imageRenameArr = array();
        $imageSizeArr = array();
        $imageExtensionArr = array();
        $imagePathArr = array();
        foreach ($imageNames as $key => $imageName)
        {
            $imageExtension = pathinfo($imageName, PATHINFO_EXTENSION);
            $imagerename = 'image_' . time() . '_' . $key . '.' . $imageExtension;
            $imageSaveLocation = '../4assets/images/'.$imagerename;
            $imageSizeBytes = filesize($imageTempNames[$key]);
            $imagesizeMB = round(($imageSizeBytes / 1024) / 1024, 2);
            $allowed_extensions = array("jpeg", "jpg", "png");
            if($imagesizeMB > 5) {
                $_SESSION['error'] = 'File size must be less than 5MB.';
                header('location:../2view/index.php');
                exit();
            } else if(!in_array($imageExtension, $allowed_extensions)) {
                $_SESSION['error'] = 'Extension not allowed, please choose a JPEG, JPG, or PNG file.';
                header('location:../2view/index.php');
                exit();
            } else {
                if(move_uploaded_file($imageTempNames[$key], $imageSaveLocation)) {
                    $imageRenameArr[] = $imagerename;
                    $imageSizeArr[] = $imagesizeMB;
                    $imageExtensionArr[] = $imageExtension;
                    $imagePathArr[] = $imageSaveLocation;
                    $_SESSION['success'] = 'Image uploaded successfully.';
                } else {
                    $_SESSION['error'] = 'Error uploading image.';
                    header('location:../2view/index.php');
                    exit();
                }
            }
        }
        $imageNameString = implode(",", $imageRenameArr);
        $imageSizeString = implode(",", $imageSizeArr);
        $imageExtensionString = implode(",", $imageExtensionArr);
        $imagePathString = implode(",", $imagePathArr);
        $insert_record = mysqli_query($conn, "INSERT INTO `multiple_images` (`image_name`,`size`, `extension`,`path`) VALUES ('$imageNameString','$imageSizeString','$imageExtensionString','$imagePathString')");
        if($insert_record)
        {
            $_SESSION['success'] = 'Image uploaded successfully.';
            header('location:../2view/index.php');
        }
        else
        {
            $_SESSION['error'] = 'Error uploading image to database.';
            header('location:../2view/index.php');
        }
    }
?>

This PHP script facilitates the process of uploading multiple images through a web form and handling the subsequent processing of each uploaded image. Upon form submission, the script first initializes output buffering and session handling. It then includes a file responsible for database connection. The script checks if the form has been submitted by verifying the presence of a specific POST parameter. If the form has been submitted, it begins processing the uploaded images individually. 

For each image, it generates a unique name based on the current timestamp and loop index. Subsequently, it validates the size and extension of the image. If the image size exceeds 5MB or the extension is not supported (limited to 'jpeg', 'jpg', or 'png'), it sets an error message in the session and redirects the user back to the form page. Valid images are moved to a specified server location, and their details are stored in arrays. After processing all uploaded images, the script constructs comma-separated strings containing information about the images (name, size, extension, and path). It then constructs an SQL query to insert this information into a database table named 'multiple_images'. If the insertion is successful, it sets a success message in the session and redirects the user back to the form page. 

Conversely, if the insertion fails, it sets an error message in the session and redirects the user back to the form page. In summary, this script facilitates the uploading, validation, storage, and database insertion of multiple images while providing feedback to the user through session-based messaging and redirection.

Post a Comment

Previous Post Next Post

Recent in Technology