Upload and Store Image File in Database using PHP and MySQL

Upload and Store Image File in Database using PHP and MySQL

In this tutorial, we are going to learn "how to upload 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 pictures in PHP".

Image Upload 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>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. ob_start() and session_start(): These are PHP functions used to start output buffering and initialize a session, respectively. Output buffering allows you to store output in memory instead of sending it to the client immediately, which can be useful for handling headers and sessions. Sessions are used to persist data across multiple page requests for a single user.

2. require_once('../1config/conn.php'): This line includes a PHP file (conn.php) that likely contains database connection settings or other configuration variables necessary for the script to function properly.

3. HTML structure: The code then proceeds to define the HTML structure for the webpage, including the <!DOCTYPE html> declaration, <html>, <head>, and <body> tags.

4. Meta tags and title: Meta tags for character set and viewport settings are included within the <head> section. The page title is set to "Image Upload."

5. require_once('../1config/all_css.php'): This line includes another PHP file (all_css.php) that likely contains links to CSS files for styling the webpage.

6. Container and card elements: The main content of the page is contained within a <div> with the class container and card. Inside the card, there is a card header with the title "Image upload in PHP."

7. Form for uploading images: Within the card body, a form is defined with action="../3management/upload.php", which suggests that upon form submission, the data will be sent to upload.php for processing. The form uses the POST method and enctype="multipart/form-data" attribute to handle file uploads. It contains an input field of type file for selecting images and a submit button.

8. PHP code for displaying alerts: Within the form, there is PHP code that checks if there are any success or error messages stored in the session ($_SESSION). If messages are present, they are displayed as alert boxes, and the session variables are unset to clear them from the session.

9. Image preview: Below the file input field, there is an <img> tag with the src attribute set to a placeholder image (../4assets/product-placeholder.jpg). This tag is initially set to display a default image, and JavaScript may be used to update its source to preview the selected image before uploading.

10. require_once('../1config/all_js.php'): This line includes another PHP file (all_js.php) that likely contains links to JavaScript files for scripting functionality on the webpage.

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']))
    {
        $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();
            }
        }        
    }
?>

Image Upload In PHP


This PHP script orchestrates the process of handling image uploads submitted through a web form. Upon form submission, the script first initializes output buffering and session management to ensure seamless operation and data persistence across page requests. It then includes a configuration file (`conn.php`) containing essential settings, likely pertaining to database connectivity. The script verifies if the form submission includes the designated 'uploadbutton' field, indicating an image upload request. If so, it extracts details about the uploaded image such as its name, temporary name, and extension. A unique filename is generated incorporating a timestamp to prevent naming conflicts, and the intended save location is determined within the server's directory structure. Subsequently, the script checks the size of the uploaded image, ensuring it does not exceed a predefined limit of 5 megabytes, and validates that the file extension is among the accepted types, including JPEG, JPG, and PNG. If either criterion is violated, an appropriate error message is stored in the session, and the user is redirected back to the upload form page (`../2view/index.php`). Upon successful validation, the script attempts to insert a record into the designated database table ('images') containing pertinent details about the uploaded image, such as its name, size, extension, and path. If the insertion operation succeeds, the script moves the uploaded image to the specified directory on the server, sets a success message in the session, and redirects the user back to the upload form page. Conversely, if the insertion fails, an error message is stored in the session, and the user is redirected to the form page to retry the upload. This comprehensive script thus ensures a secure and systematic approach to image uploading, encompassing validation, database interaction, and user feedback.

Post a Comment

Previous Post Next Post

Recent in Technology