PHP Tutorials

PHP 8 Upload & Store File/Image in MySQL Tutorial

This is a step by step PHP 8 file uploading and storing tutorial. In this tutorial, we will learn how to upload files and images in MySQL Database. and how to implement file upload validation before sending it to a web server.

The Internet has never been a secure place; an army of malicious hackers may take advantage of your code that can bring severe damages to your php application.

Before uploading the file to the server, we must make sure the necessary file validation is done correctly. If we do not consider security factors, we might get into trouble.

PHP 8 File Upload Tutorial Example

  • Display image preview before uploading
  • Place all the uploaded images in a specific folder
  • Store images path in the MySQL database

Along with that we will also cover the following image validation using PHP 8:

  • Check if the real image is uploaded
  • Allow only specific file extension such as .jpg, .jpeg or .png
  • Make sure file size should not exceed 2MB
  • Check if the file already exists

Getting Started

Start MAMP or XAMPP, create the following folder and file structure in htdocs directory.

\-- php-file-upload
  |-- config
      |--- database.php
  |-- img_dir
      |--- image-1
      |--- image-2
  |-- file-upload.php
  |-- index.php

Create Database & Table

Create database `database_name`.

Create `table_name` inside the database.

You can execute the following command to create the table columns to store the images in the database.

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

Create File Uploading Form

Create an HTML form that permits our users to select the image from their local device the same image which they want to store onto the server.

The input type should be set to file along with the name property.

Also, define the method=”post” and enctype=”multipart/form-data” tags.

<form action="" method="post" enctype="multipart/form-data" class="mb-3">
  <h3 class="text-center mb-5">Upload File in PHP 8</h3>

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

Display Image Preview

You can show image preview before uploading it to the server with the help of jQuery.

Import jQuery CDN link before the closing body tag.

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

We have already declared the image tag with the blank src=”” tag.

<img src="..." id="imgPlaceholder" alt="">

The following function converts the image string and places the base64 url in the HTML img tag when the user selects the image.

Place the following code right after the jQuery CDN script tag.

<script>
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
          $('#imgPlaceholder').attr('src', e.target.result);
        }

        // base64 string conversion
        reader.readAsDataURL(input.files[0]);
      }
    }

    $("#chooseFile").change(function () {
      readURL(this);
    });
</script>

Database Configuration

Add following code in config/database.php file to make the PHP connection with MySQL database using PDO method.

// config/database.php

<?php

    $hostname = "localhost";
    $username = "root";
    $password = "";

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

?>

File/Image Upload Validation in PHP 8

Let us add our first validation with the help of the file_exists() PHP method. Display error message to the user if he does not select any image.

To address the errors, we set up a $resMessage array with status and message properties. We will display the messages to the user based on the response on the front-end.

if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {
    $resMessage = array(
        "status" => "alert-danger",
        "message" => "Select image to upload."
    );
}

The following code applies the validation that allows specific file type such as .jpg, jpeg and .png to be uploaded on the server. You won’t be allowed other file types, and will be displayed error message if you do so.

// Get file extension
$imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Allowed file types
$allowd_file_ext = array("jpg", "jpeg", "png");

else if (!in_array($imageExt, $allowd_file_ext)) {
    $resMessage = array(
        "status" => "alert-danger",
        "message" => "Allowed file formats .jpg, .jpeg and .png."
    );
}

Set up image file size limit using the following code. A user can not allow more than 2MB size of image to upload.

else if ($_FILES["fileUpload"]["size"] > 2097152) {
    $resMessage=array("status"=> "alert-danger",
        "message"=> "File is too large. File size should be less than 2 megabytes."
    );
}

The given below code checks if the current file is already uploaded.

else if (file_exists($target_file)) {
    $resMessage = array(
        "status" => "alert-danger",
        "message" => "File already exists."
    );
}

Create img_dir folder in the root of your PHP upload file project, here we will store all the uploaded images.

<?php 

    // Database connection
    include("config/database.php");
    
    if(isset($_POST["submit"])) {
        // Set image placement folder
        $target_dir = "img_dir/";
        // Get file path
        $target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);        

        if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {
            // Validation goes here
        } else {
            if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
                $sql = "INSERT INTO user (file_path) 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 coudn't be uploaded."
                );
            }
        }

    }

?>

Complete PHP 8 File Upload Example

Complete PHP file upload code example can be found in the file-upload.php file.

// file-upload.php

<?php 

    // Database connection
    include("config/database.php");
    
    if(isset($_POST["submit"])) {
        // Set image placement folder
        $target_dir = "img_dir/";
        // 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" => "File already exists."
            );
        } else {
            if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {
                $sql = "INSERT INTO user (file_path) 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 coudn't be uploaded."
                );
            }
        }

    }

?>

Include the file-upload.php in the index.html file here we have defined the file upload form along with the message array.

<?php include("file-upload.php"); ?>

<!doctype html>
<html lang="en">

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

  <title>PHP 8 Image Upload Example</title>
  <style>
    .container {
      max-width: 450px;
    }
  </style>
</head>

<body>

  <div class="container mt-5">
    <form action="" method="post" enctype="multipart/form-data" class="mb-3">
      <h3 class="text-center mb-5">Upload File in PHP</h3>

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

    <!-- Display response messages -->
    <?php if(!empty($resMessage)) {?>
    <div class="alert <?php echo $resMessage['status']?>">
      <?php echo $resMessage['message']?>
    </div>
    <?php }?>
  </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>

Conclusion

We have completed the PHP 8 File Upload tutorial, and we learned how to upload and store image using PHP in MySQL database. I hope you liked this tutorial.

The complete code of this tutorial can be found on GitHub.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.

Recent Posts

React Display Validation Error Messages with Hook Form Tutorial

As a React developer, you must know how to implement validation in form, and a…

2 days ago

React Hook Form 7 Required Checkbox Validation Tutorial

Creating checkboxes in React is not so difficult, especially when you are using React Hook…

5 days ago

React Hook Form 7 Custom Radio Buttons Tutorial

Learning React is not complicated; instead, it's easy, but only when you have the right…

1 week ago

React Bootstrap Custom Dropdown List with Fetch API Tutorial

Dropdown is a valuable and prominent module, which is often used to select one option…

2 weeks ago

React Hook Form Reset / Clear Form Values and Errors Tutorial

React form reset tutorial; Forms are handy provides the best possible way to get information…

2 weeks ago

React Show Loading Spinner on Submit Click Tutorial

You click on the submit button, form is processed, but nothing is being shown to…

2 weeks ago