PHP Image Upload Using DropzoneJs

Last modified on August 17th, 2018 by Vincy.

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.

photo-preview

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.

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.

CREATE TABLE IF NOT EXISTS `images_info` (
`image_id` int(11) NOT NULL,
`image_name` varchar(200) NOT NULL,
`image_path` varchar(200) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`image_id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8; 

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.

<?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 ("db.php");
    print $sql = "INSERT INTO images_info (image_path) VALUES ('" . $imagePath . "')";
    mysqli_query($conn, $sql);
    $current_id = mysqli_insert_id($conn);
}
?>
<html>
<head>
<title>Add New Image</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />

<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
</head>
<body>
    <form name="frmImage" action="image-add.php?action=save"
        class="dropzone"></form>
    <div class="btn-menu">
        <a href="index.php" class="link">Back to List</a>
    </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.

<?php
require_once ("db.php");
$sql = "SELECT * FROM images_info ORDER BY image_id DESC";
$result = mysqli_query($conn, $sql);
?>
<html>
<head>
<title>Images List</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>

<body>
    <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="link">Add Image</a>
            </div>
            <table border="0" cellpadding="10" cellspacing="1"
                width="100%" class="tblListForm">
                <tr class="listheader">
                    <td>Image Path</td>
                    <td>Added at</td>
                    <td>Action</td>
                </tr>
<?php
$i = 0;
while ($row = mysqli_fetch_array($result)) {
    ?>
<tr class="row">
                    <td><?php echo $row["image_path"]; ?></td>
                    <td width="25%"><?php echo date("d-m-Y", strtotime($row["date"])); ?></td>
                    <td width="20%"><a
                        href="image-edit.php?image_id=<?php echo $row["image_id"]; ?>"
                        class="link"><img alt='Edit' title='Edit'
                            src='icons/edit.png' class="action-icon" /></a>
                        <a
                        href="image-delete.php?image_id=<?php echo $row["image_id"]; ?>"
                        class="link"><img alt='Delete' title='Delete'
                            src='icons/delete.png' class="action-icon" /></a></td>
                </tr>
<?php
    $i ++;
}
?>
</table>
    
    </form>
    </div>
</body>
</html>

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.

<?php
require_once ("db.php");
$imagePath = "";

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'];
    
    $selectQuery = "select image_path from images_info where image_id='" . $_GET["image_id"] . "'";
    
    $resultSelectQuery = mysqli_query($conn, $selectQuery);
    $image = mysqli_fetch_array($resultSelectQuery, MYSQLI_ASSOC);
    
    if (move_uploaded_file($tempFile, $targetFile)) {
        
        if (! unlink($image[image_path])) {
            echo ("Error deleting $image");
        } else {
            echo ("Deleted $image");
        }
    } else {
        echo "false";
    }
}

if (! empty($_GET["action"]) && $_GET["action"] == "save") {
    $sql = "UPDATE images_info SET image_path ='" . $imagePath . "' WHERE image_id ='" . $_GET["image_id"] . "'";
    mysqli_query($conn, $sql);
    $message = "Record Modified Successfully";
}

$select_query = "SELECT * FROM images_info WHERE image_id='" . $_GET["image_id"] . "'";
$result = mysqli_query($conn, $select_query);
$row = mysqli_fetch_assoc($result);
?>
<html>

<head>
<title>Edit Image</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />

<link rel="stylesheet" type="text/css" href="dropzone/dropzone.css" />
<script type="text/javascript" src="dropzone/dropzone.js"></script>
</head>

<body>

    <div class="box-preview">
        <img src="<?php echo $row["image_path"]; ?>" />
        <div class="preview-footer"><?php echo $row["image_path"]; ?></div>
    </div>

    <form name="frmImage"
        action="image-edit.php?action=save&image_id=<?php echo $_GET['image_id']?>"
        class="dropzone"></form>
    <div class="btn-menu">
        <a href="index.php" class="link">Back to List</a>
    </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.

<?php
require_once ("db.php");

if (isset($_GET["image_id"])) {
    $imageId = $_GET["image_id"];
}

$sql = "DELETE FROM images_info WHERE image_id='" . $imageId . "'";
mysqli_query($conn, $sql);

header("Location:index.php");
?>

PHP Image Upload Using DropzoneJs – Output

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.

php-image-upload-using-dropzonejs

Download

This PHP code tutorial was published on January 2, 2018.

↑ Back to Top

Share this Article