Image Upload Using Dropzone in PHP with Example

Image upload functionality is a common requirement in many web applications. This tutorial will explore how to implement image uploads using Dropzone.js in PHP.

Dropzone.js is a popular JavaScript library that provides an elegant drag-and-drop file upload experience for users. By combining Dropzone.js with PHP, you can create a seamless image upload process on your website. Let’s take a practical code example.

Before starting make sure you have a web server and PHP installed in your machine. Create a new project directory for this example.

Download Dropzone.js from the official website or you can include CDNs. For this example, we will download and extract the contents and have those files in our HTML file. Make sure to place them in the appropriate locations within your project structure.

Create a new file in your project directory by index.php name. In this file first of all we’ll create a simple HTML element. This element will be used to render Dropzone functionality.

After creating HTML content will add code to initialize Dropzone with some Dropzone properties like maximum file selection and action URL.

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Using Dropzone in PHP</title>
    <link rel="stylesheet" href="../dropzone.css">
</head>
<body>
    <div id="dropzoneContainer" class="dropzone"></div>
    <script src="../dropzone.js"></script>
    <script>
        // Initialize Dropzone.js
        Dropzone.options.dropzoneContainer = {
            url: "upload.php",
            acceptedFiles: "image/*",
            maxFilesize: 5, // in megabytes
            maxFiles: 5
        };
    </script>
</body>
</html>

In the above code, we have included library files for Dropzone which are CSS and JS. Then added div with the dropzone class. In a script, we have initialized dropzone with URL, accepted file type, maximum files the user can upload, and max file count.

Now, Let’s add PHP code to upload files from the user’s computer to the server. So we can use it once uploading is completed.

Update the index file as below:

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Using Dropzone in PHP</title>
    <link rel="stylesheet" href="path/to/dropzone.css">
</head>
<body>
    <div id="dropzoneContainer" class="dropzone"></div>
    <script src="path/to/dropzone.js"></script>
    <script>
        // Initialize Dropzone.js
        Dropzone.options.dropzoneContainer = {
            url: "upload.php",
            acceptedFiles: "image/*",
            maxFilesize: 5, // in megabytes
            maxFiles: 5
        };
    </script>

    <?php
    $targetDir = "uploads/"; // Directory to store uploaded images
    $allowedExtensions = array("jpg", "jpeg", "png"); // Allowed file extensions

    // Check if the directory exists, otherwise create it
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }

    // Handle the image upload
    if (!empty($_FILES['file']['name'])) {
        $fileName = basename($_FILES['file']['name']);
        $targetPath = $targetDir . $fileName;
        $fileExtension = strtolower(pathinfo($targetPath, PATHINFO_EXTENSION));

        // Validate file extension
        if (in_array($fileExtension, $allowedExtensions)) {
            // Move the uploaded file to the target directory
            if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
                // Image upload success
                echo "Image uploaded successfully!";
            } else {
                // Image upload failed
                echo "Failed to upload image.";
            }
        } else {
            // Invalid file extension
            echo "Invalid file format. Only JPG, JPEG, and PNG files are allowed.";
        }
    }
    ?>
</body>
</html>

The above changes will handle file upload functionality and show the user status of upload or error message whenever something goes wrong.

The code checks if the directory exists and if it’s not found then it will create a new one. Then, it checks if an image file was uploaded ($_FILES[‘file’][‘name’]), retrieves its name, and constructs the target path. The code verifies if the file extension is allowed and uses move_uploaded_file() to move the temporary uploaded file to the target directory.

At last, it will change file moved successfully or not, and based on the results it will print a message to the user.

To test, open your web browser and test the image upload functionality. Drag and drop an image into the Dropzone container or use the provided button/link to choose an image file from your local system. Verify that the image is successfully uploaded and processed and that the appropriate success message is displayed.

Conclusion

By following this tutorial, you have learned how to implement image uploads using Dropzone.js in PHP. It’s a simple example however there are plenty of configuration options available, you can use it as per your requirements. You can also perform compression, resizing, and much more on the PHP side.