Share this:

This tutorial will walk you through the process of uploading and storing files in PHP 8. This tutorial will teach you how to upload files and images to a MySQL database. and how to validate file uploads before sending them to a web server.

The Internet has never been a safe haven; an army of malicious hackers may exploit your code, causing severe damage to your php application.

We must ensure that the necessary file validation is performed correctly before uploading the file to the server. We may get into trouble if we do not consider security factors.

How to Convert PHP Arrays to String with Implode() in PHP 8

PHP TUTORIAL

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

In addition, we will go over the following image validation techniques 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

Table of Contents

  1. Getting Started
  2. Create Database & Table
  3. Create File Upload Form
  4. Display Image Preview
  5. Database Configuration
  6. File/Image Upload Validation in PHP
  7. Complete PHP File Upload Example
  8. Conclusion

Getting Started

Start MAMP or XAMPP and create the folder and file structure shown below in the 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.

To create the table columns needed to store the images in the database, run the following command.

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 allows our users to select an image from their local device that they want to save to the server.

Along with the name property, the input type should be set to file.

Define the method=”post” and enctype=”multipart/form-data” tags, as well.

<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

Using jQuery, you can display an image preview before uploading it to the server.

Before the closing body tag, include the jQuery CDN link.

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

With the blank src=”” tag, we’ve already declared the image tag.

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

When the user selects an image, the following function converts the image string and inserts the base64 url into the HTML img tag.

After the jQuery CDN script tag, add the following code.

<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 the following code to the config/database.php file to connect PHP to the MySQL database using the 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’s add our first validation using the file exists() PHP method. If the user does not select an image, an error message is displayed.

We created a $resMessage array with status and message properties to address the errors. The messages will be displayed 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 implements validation, allowing specific file types such as.jpg, jpeg, and.png to be uploaded to the server. Other file types are not permitted and will result in an error message.

// 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."
    );
}

Use the following code to set an image file size limit. A user cannot upload images larger than 2MB in size.

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 code below checks to see if the current file has already been uploaded.

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

Create an img dir folder in the root of your PHP upload file project to store all 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

The file-upload.php file contains a complete PHP file upload code example.

// 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, where the file upload form and message array are defined.

<?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 finished the PHP 8 File Upload tutorial and learned how to upload and store images in a MySQL database using PHP. I hope you found this tutorial useful.

This tutorial’s source code is available on GitHub.

Share this:

Categorized in: