PHP Image Upload Using DropzoneJs

by Vincy. Last modified on March 25th, 2024.

In this article, I will walk you through to implement image upload using DropzoneJS. It provides a nice and flexible interface it to the user. It allows the user to upload files by using drag and drop.

Also, it allows the users to explore the files and folders for choosing files to be uploaded via Dropzone. Below, we are going to see an example code for uploading images via DropzoneJS using PHP.

In this example, we have created image drop zone by initializing the DropzoneJS library. The uploaded image path will be stored in the database. I added CRUD actions in this example to manage the uploaded image information in the database.

The database table image_info contains columns to store the auto-generated unique image id, image path where it is uploaded and the date/time when it is added.

This screenshot shows the edit form with the existing image preview and a Dropzone to let the user upload the new image to replace the existing one. Refer these earlier articles, if you plan to implement this on your own PHP AJAX image upload and  jQuery drag and drop article.

dropzone image edit with preview

Database Table image_info

The following SQL script is used to create the image_info database table before getting started with the Dropzone image upload and its CRUD actions.

I have given the complete SQL script which is to be imported while setting this example code in your development environment.

structure.sql

CREATE TABLE `images_info` (
  `image_id` int(11) NOT NULL,
  `image_path` varchar(200) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);


ALTER TABLE `images_info`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `images_info`
--
ALTER TABLE `images_info`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;

Upload and Add New Image via Dropzone

The following code shows the HTML for creating dropzone with the reference of an HTML form element. In this code, I included the DropzoneJs and the CSS to create the user interface for uploading images.

The HTML form action URL is mapped to the events of the Dropzone element. On successful image file drop event, the form action URL will be called to execute the PHP file upload script. After uploading the image to the folder then the file path is added to the database.

image-add.php

<?php
if (! empty($_FILES)) {
    $imagePath = isset($_FILES["file"]["name"]) ? $_FILES["file"]["name"] : "Undefined";
    $targetPath = "uploads/";
    $imagePath = $targetPath . $imagePath;
    $tempFile = $_FILES['file']['tmp_name'];
    $targetFile = $targetPath . $_FILES['file']['name'];
    if (move_uploaded_file($tempFile, $targetFile)) {
        echo "true";
    } else {
        echo "false";
    }
}
if (! empty($_GET["action"]) && $_GET["action"] == "save") {
    require_once __DIR__ . '/DataSource.php';
    $database = new DataSource();
    $sql = "INSERT INTO images_info (image_path) VALUES(?)";
    $paramType = 's';
    $paramValue = array(
        $imagePath
    );
    print $current_id = $database->insert($sql, $paramType, $paramValue);
}
?>
<html>
<head>
<title>Add New Image</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
</head>
<body>
    <div class="phppot-container">
        <form name="frmimage" action="image-add.php?action=save"
            class="dropzone"></form>
        <div class="row">
            <a href="index.php" class="mr-20">Back to List</a>
        </div>
    </div>
</body>
</html>

List Image Data from Database

The following code is used to fetch the MySQL database table result to list the image information. Each row of image information will have the edit/delete action icons to handle the update and the delete actions.

index.php

<?php
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
$sql = "SELECT * FROM images_info ORDER BY image_id DESC";
$result = $database->select($sql);
?>
<html>
<head>
<title>Images List</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/table.css" />
</head>
<body>
    <div class="phppot-container">
        <form name="frmImage" method="post" action="">
            <div>
                <div class="message">
                <?php if(isset($message)) { echo $message; } ?>
                </div>
                <div class="btn-menu" align="right"
                    style="padding-bottom: 5px;">
                    <a href="image-add.php" class="font-bold">Add Image</a>
                </div>
                <table class="striped">
                    <thead>
                        <tr>
                            <th>Image Path</th>
                            <th>Added at</th>
                            <th>Action</th>
                        </tr>
                    </thead>
<?php
$i = 0;
if (is_array($result) || is_object($result)) {
    foreach ($result as $key => $value) {
        ?>
<tr>
                        <td><?php echo $result[$key]["image_path"]; ?></td>
                        <td><?php echo date("d-m-Y", strtotime($result[$key]["date"])); ?></td>
                        <td><a
                            href="image-edit.php?image_id=<?php echo $result[$key]["image_id"]; ?>"
                            class="mr-20">Edit</a> <a
                            href="image-delete.php?image_id=<?php echo $result[$key]["image_id"]; ?>"
                            class="mr-20"
                            onclick="return confirm('Are you sure you want to delete this item')">Delete</a></td>
                    </tr>
<?php
        $i ++;
    }
}
?>
</table>
            </div>
        </form>
    </div>
</body>
</html>

uploaded image list

Edit Existing Image Dropzone

In this code, I show the HTML for showing the preview of the existing image and to display dropzone with the reference of the edit form class attribute as we have done with the Add action.

While uploading the existing image, the old image will be cleared from the database and from the target folder.

image-edit.php

<?php
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
if (! empty($_FILES)) {
    $imagePath = isset($_FILES["file"]["name"]) ? $_FILES["file"]["name"] : "Undefined";
    $targetPath = "uploads/";
    $imagePath = $targetPath . $imagePath;
    $tempFile = $_FILES['file']['tmp_name'];
    $targetFile = $targetPath . $_FILES['file']['name'];
    $sql = "select image_path from images_info where image_id=?";
    $paramType = 'i';
    $paramValue = array(
        $_GET["image_id"]
    );
    $image = $database->select($sql, $paramType, $paramValue);
    if (move_uploaded_file($tempFile, $targetFile)) {
        if (file_exists($image[0]['image_path'])) {
            if (! unlink($image[0]['image_path'])) {
                echo ("Error deleting $image");
            } else {
                echo ("Deleted " . $image[0]['image_path']);
            }
        }
    } else {
        echo ("Problem in uploading the file in dropzone.s");
    }
    if (! empty($_GET["action"]) && $_GET["action"] == "save") {
        $query = "UPDATE images_info SET  image_path=? WHERE image_id=?";
        $paramType = 'si';
        $paramValue = array(
            $imagePath,
            $_GET["image_id"]
        );
        $id = $database->update($query, $paramType, $paramValue);
    }
    exit();
}
$sql = "select * from images_info where image_id=? ";
$paramType = 'i';
$paramValue = array(
    $_GET["image_id"]
);
$result = $database->select($sql, $paramType, $paramValue);
?>
<html>
<head>
<title>Edit Image</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
<style>
.box-preview {
    width: 300px;
    margin: 30px auto;
    border: 10px #f3f3f6 solid;
    border-radius: 2px;
}

.box-preview img {
    width: 100%;
}

.preview-footer {
    padding: 10px 0px;
    background: #f3f3f6;
    color: #4e4e4e;
}
</style>
</head>
<body>
    <div class="box-preview">
        <img src="<?php echo $result[0]["image_path"]; ?>" />
        <div class="preview-footer"><?php echo $result[0]["image_path"]; ?></div>
    </div>
    <div class="phppot-container">
        <form name="frmImage"
            action="image-edit.php?action=save&image_id=<?php echo $_GET['image_id']?>"
            class="dropzone"></form>
        <div class="row">
            <a href="index.php" class="mr-20">Back to List</a>
        </div>
    </div>
</body>
</html>

And the code to delete the existing image record also will clear the database record and also the file from the folder by using PHP unlink() function.

image-delete.php

<?php
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
if (isset($_GET["image_id"])) {
    $sql = "DELETE FROM images_info WHERE image_id=?";
    $paramType = "i";
    $paramValue = array(
        $_GET["image_id"]
    );
    $database->delete($sql, $paramType, $paramValue);
}
header("Location:index.php");
exit();
?>

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Image Upload Using DropzoneJs”

  • Stefan says:

    Hi Vincy,
    I was looking for an easy to understand, wrking sample of image upload with Dropzone.
    Yours is the best I found and it will enable me to go on from there.

    Thank you very much for sharing your wonderful work.

    Cheers from Austria
    Stefan

Leave a Reply

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

↑ Back to Top

Share this page