How to upload multiple image in PHP

Today we will understand a PHP code that can be used to upload multiple images. This tutorial will explain step-by-step how you can upload multiple images simultaneously to your website through PHP.

Upload Image In PHP

1. PHP Files and Project Structure

First of all we need to understand what the structure of the project is. Are there some important files in the project that will help in uploading images. There will be some specific folders and files inside your project, which you need to understand.

1config - This folder contains configuration files, such as `all_css.php`, `all_js.php`, and `conn.php` that manage database connections and front-end dependencies.
2view - This folder handles the user interface, such as HTML forms, which give the user the option to upload images.
3management - This folder contains the back-end logic that processes images and saves them to the database.
4assets - This folder contains images and CSS/JS files that control the front-end design.

Step 1: Include Karna in CSS and JS file

Firstly include our `all_css.php` and `all_js.php` file which load external styles and scripts.

`all_css.php`


    <?php
        echo "<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN' crossorigin='anonymous'>";
        echo "<link rel='stylesheet' href='../4assets/css/style.css'>";
    ?>


Explanation:

1. We have linked Bootstrap CSS from CDN so that our form and page design looks good.
2. We have also linked our custom CSS file so that you can customize the style of your website.

`all_js.php`

    <?php
        echo "<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js' integrity='sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==' crossorigin='anonymous' referrerpolicy='no-referrer'></script>";
        echo "<script src='../4assets/js/index.js'></script>";
    ?>


Explanation:

* We have linked jQuery's CDN so we can implement interactive features.
* Our custom JavaScript file is also linked which manages image previews and alert messages.

Step 2: Database Connection (conn.php)

Your code has a file `conn.php`, which works to establish a connection with the database.

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


Explanation:

* Whether the `mysqli_connect()` function is used to connect to the database in the file.
* If the connection fails then the error message is shown for the `die()` function.

Step 3: Image Upload Form (index.php)

Now we will understand our HTML form which gives the user the option to upload an image.

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


Explanation:

  1. This form gives the user the option to select multiple images. We have used `<input type='file' name='images[]' multiple>` so that the user can select images at once.
  2. The form is sent to the `upload.php` file via the `POST` method.
Upload Image In PHP

Step 4: Backend Image Upload Logic (upload.php)

When the user submits the form, the `upload.php` file takes over the processing of the image.


    <?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');
            }
        }
    ?>

Explanation:

  1. We validate all uploaded images. Check the image size (must not exceed 5 MB), and verify the file extension (only `.jpg`, `.jpeg`, and `.png` are allowed).
  2. If the image is uploaded successfully, we save its name, size, extension, and path to the database.

Step 5: Front-end JavaScript Logic (index.js)

Finally, we use JavaScript to make our front-end a little interactive.


    setTimeout(function(){
        $('.alert').fadeOut('slow');
    }, 5000);


    $(document).ready(function() {
        $('#selectimage').on('change', function () {
            let image = $(this).prop('files')[0];
            $('#imageobject').attr('src', URL.createObjectURL(image));
        });
    });


Explanation:

* The alert messages from the `setTimeout()` function fade out after 5 seconds.
* When the user selects an image with `$('#selectimage').on('change', function() {...})`, the tab image is displayed as a preview on the page.

Conclusion

This was a simple and effective PHP script used to upload multiple images. You can integrate this code into your project and upload images easily.

Post a Comment

Previous Post Next Post