File Upload & Store in PHP 8

In this blog, We will learn how to upload a File using PHP 8 and Store it with OOPS Concept. File Upload & Store in PHP 8.

How to Upload File in PHP8 with PDO

How to implement file upload validation before sending it to a web server. We will do a proper validation in our code. I will create a simple form with help of HTML and CSS.

Now first I will create a Database for storing file names in it. So make a database with a table named users. Please see the below command :

CREATE TABLE `user` (
    `id` int(11) NOT NULL,
    `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Database configuration

Now we will see the database configuration . Please create a file inside your project directory with the named config.php I am not using any password for configuration so I leave the password field empty.

config.php

<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";

    try {
        $conn = new PDO("mysql:host=$hostname;dbname=file_upload", $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();
    }
?>

Our Database configuration has been created successfully. Now we can go ahead with the File upload logic. You can use this logic in your big project according to your use but make sure Your code must have proper validation on the client-side as well as the server side.

Now create a file with a named index.php this is our main page or you can say a landing page. You can any name to index.php but then you have to mention the page on URL like http://localhost/FileUpload.php

index.php

<?php include("store.php"); ?>
<!doctype html>
<html lang="en">
<head>
    <title>PHP 8 Image Upload Example</title>
    <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">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-2">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">PHP 8 Image Upload Example</h3>
                    </div>
                    <div class="card-body">
                        <!-- Display response messages -->
                        <?php if(!empty($resMessage)) {?>
                            <div class="alert <?php echo $resMessage['status']?>">
                                <?php echo $resMessage['message']?>
                            </div>
                        <?php }?>
                        <form action="" method="post" enctype="multipart/form-data" class="mb-3">
                            <div class="user-image mb-3 text-center">
                                <div style="width: 100px; height: 100px; overflow: hidden; background: #cccccc; margin: 0 auto">
                                    <img src="..." class="figure-img img-fluid rounded" id="imgPlaceholder" alt="">
                                </div>
                            </div>
                            <div class="custom-file">
                                <input type="file" name="fileUpload" class="custom-file-input" id="chooseFile">
                                <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 File
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script>
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#imgPlaceholder').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]); // convert to base64 string
            }
        }
        $("#chooseFile").change(function () {
            readURL(this);
        });
    </script>
</body>
</html>

Now create another file for storing the data with named save.php

save.php

<?php 
    // Database connection
    include("config.php");
    
    if(isset($_POST["submit"])) {
        // Set image placement folder
        $target_dir = "images/";
        // Get file path
        $target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);
        // Get file extension
        $imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        // Allowed file types
        $allowd_file_ext = array("jpg", "jpeg", "png");

        if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {
           $resMessage = array(
               "status" => "alert-danger",
               "message" => "Select image to upload."
           );
        } else if (!in_array($imageExt, $allowd_file_ext)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "Allowed file formats .jpg, .jpeg and .png."
            );            
        } else if ($_FILES["fileUpload"]["size"] > 2097152) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "File is too large. File size should be less than 2 megabytes."
            );
        } else if (file_exists($target_file)) {
            $resMessage = array(
                "status" => "alert-danger",
                "message" => "The File already exists."
            );
        } else {
            if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
                $sql = "INSERT INTO user (image) VALUES ('$target_file')";
                $stmt = $conn->prepare($sql);
                if($stmt->execute()){
                    $resMessage = array(
                        "status" => "alert-success",
                        "message" => "Image uploaded successfully."
                    );                 
                 }
            } else {
                $resMessage = array(
                    "status" => "alert-danger",
                    "message" => "Image can not be uploaded."
                );
            }
        }
    }
?>

Our Code is completed here, Now you can run the project using the below command

php -S localhost:8000

Now go to the browser and open this URL

http://localhost:8000/

See our More tutorials on PHP8 and REACT

How to Highlight a Deleted Row in PHP

Send Email using PHP

Codeigniter 4 CRUD Operation With Ajax Example

Netflix clone app using Laravel

login form in React with Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *