How to Upload and Store Images in PHP & MySQL with Preview and Error Handling

In today's article, we will understand the process of uploading images in PHP step by step. We have an example of a simple image upload system which explains the code of different files. This article will be very simple and detailed in which the code of each file is explained.

Uploading images in PHP is a common task when you have to allow users to upload images on the website. In this guide, we are going to see the complete code of the image upload system, in which the function and role of each file is explained.

Upload Image In PHP

PHP Configuration for Database Connection (conn.php)

First, we need to set up a database connection in our PHP project. For this we use the `conn.php` file. In this file we create a connection to our database which is required for image upload and other tasks.

Code Explanation:


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

  1. $hostname: In this we put the name or address of our server. Localhost means your local development server.
  2. $username and $password: These are the login credentials of your database. By default, `root' password is given and if you have not given any custom password, then the password is blank.
  3. $database: This is the database in which we will store the image information.
  4. mysqli\_connect(): This function creates the connection to the database. If the connection fails, the error message is displayed using `die()` function.

CSS (all\_css.php)

To make the image upload form look nice, we use CSS. In this case, we are using Bootstrap, a popular CSS framework.

Code Explanation:


    <?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'>";
    ?>

  1. We're including Bootstrap in the CDN. This gives us a full library of CSS to make our forms and elements look great.
  2. The second link contains our custom styles to make our forms even more personal.

JavaScript (all\_js.php)

We use JavaScript to enhance the functionality of the form. For example, when selecting an image, we want to preview the image.

Code Explanation:


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

  1. We have included jQuery library here which makes DOM manipulation very easy.
  2. The second script file `index.js` contains the docker which is responsible for image previews and alert messages.

Image Upload Form (index.php)

Now we will look at the code of the form that gives the user the option to upload an image. In the file we find the option to select an image, a button to submit the form, and a display of the image for preview.

Code Details:


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

  1. Form Structure: This form provides input fields for user to upload image. While submitting the form, data has to be passed to `upload.php` file.
  2. Image Preview: After selecting the image file, we are showing preview of image in element with `#imageobject` id.
  3. Session Message: If image upload is successful, success message is displayed, if any error occurs, error message is displayed.
Upload Image In PHP

Image Upload Logic (upload.php)

This file handles the actual logic of uploading the image. When the user selects an image and presses the submit button, the PHP file saves the image to the server and puts its information into the database.

Code Details:


    <?php
        ob_start();
        session_start();
        require_once('../1config/conn.php');
        if(isset($_POST['uploadbutton']))
        {
            $imageName = $_FILES['images']['name'];
            $imagetempname = $_FILES['images']['tmp_name'];
            $imageExtension = pathinfo($imageName, PATHINFO_EXTENSION);
            $imagerename = 'image_' . time() . '.' . $imageExtension;
            $imageSaveLocation = '../4assets/images/'.$imagerename;
            $imagesizeBytes = filesize($imagetempname);
            $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  
            {
                $insert_record = mysqli_query($conn, "INSERT INTO `images` (`name`,`size`,`extension`,`path`) VALUES ('$imagerename', '$imagesizeMB', '$imageExtension' ,'$imageSaveLocation')");
                if($insert_record)
                {
                    move_uploaded_file($imagetempname, $imageSaveLocation);
                    $_SESSION['success'] = 'Image uploaded successfully.';
                    header('location:../2view/index.php');
                    exit();
                }
                else
                {
                    $_SESSION['error'] = 'Image not uploaded successfully.';
                    header('location:../2view/index.php');
                    exit();
                }
            }        
        }
    ?>

  1. $\_FILES: We use the `$_FILES` superglobal to get image information such as file name, temporary file name, extension, etc.
  2. File validation: We validate the file size and file extension. If the file size is more than 5MB, an error message is displayed, and an error message is also displayed if the extension is not valid (only jpeg, jpg, png are allowed).
  3. Database insert: If the file is valid, the image name, size, extension, and path are inserted into the database.

Custom CSS (style.css)

With the help of custom CSS we make our form look attractive. Here are the basic styling and shadow effects.


    *
    {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: Arial, Helvetica, sans-serif;
    }
    .container
    {
        box-shadow: 10px 0 30px rgba(0,0,0,0.3);
    }
    .card-header
    {
        background: linear-gradient(-135deg, #c850c0, #4158d0);
        color: #fff;
        align-items: center;
    }
    .card-header h4
    {
        text-align: center;
    }
   

Conclusion

In this article, we have understood the whole process of uploading images in PHP step by step. We have explained the code of each file in detail and also understood its function. Can you add the image upload feature in your PHP application?

Post a Comment

Previous Post Next Post