How to Handle Image Uploads in Summernote with PHP: A Step-by-Step Guide

If you’re looking to integrate image uploads in Summernote and handle them using PHP, you’re in the right place. This tutorial will guide you through setting up multiple Summernote editors, handling image uploads, and resizing images to fit within a 200×200 pixel box while maintaining the aspect ratio. Let’s dive in!

What You’ll Need

  1. Basic HTML and PHP knowledge: This will help you understand the code snippets better.
  2. A web server with PHP support: You can use XAMPP, WAMP, or any other local server.

Step 1: Set Up Your HTML with Summernote

First, we need to create an HTML file that includes multiple Summernote editors. Each editor will have its own image upload handler.

Here’s the HTML code:

Summernote Multiple Editors
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Summernote Multiple Editors</title>
    <!-- Summernote CSS -->
    <link href="" rel="stylesheet">
    <!-- Bootstrap CSS -->
    <link href="" rel="stylesheet">
    <div class="container">
        <h1>Summernote Multiple Editors</h1>
        <textarea id="talkpoints"></textarea>
        <textarea id="company_profile"></textarea>
        <textarea id="executive_profile"></textarea>
        <textarea id="event_description"></textarea>
        <textarea id="presenceinph"></textarea>
        <textarea id="othertopicsfordiscussion"></textarea>
    <!-- jQuery -->
    <script src=""></script>
    <!-- Bootstrap JS -->
    <script src=""></script>
    <!-- Summernote JS -->
    <script src=""></script>

        $(document).ready(function() {
            var config = {
                height: 300,
                callbacks: {
                    onImageUpload: function(files) {
                        var editor = this;
                        uploadImage(files[0], editor);


        function uploadImage(file, editor) {
            let formData = new FormData();
            formData.append('file', file);

                url: 'upload.php',
                method: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    var url = JSON.parse(response).url;
                    $(editor).summernote('insertImage', url);
                error: function(xhr, status, error) {
                    console.error('Upload error:', error);

Notes on the HTML and JavaScript:

  • Summernote Initialization: Each textarea is turned into a Summernote editor using $('#elementID').summernote(config).
  • Image Upload Callback: The onImageUpload callback is triggered when an image is uploaded. It calls uploadImage with the uploaded file and the specific editor instance.
  • uploadImage Function: This function sends the image to the server using AJAX. On successful upload, it inserts the image URL back into the Summernote editor.

Step 2: Create the PHP Script to Handle Uploads

Now, let’s create the PHP script (upload.php) to handle the image upload, resizing, and validation.

if ($_FILES['file']['name']) {
    $allowedMimeTypes = ['image/gif', 'image/jpeg', 'image/png', 'image/GIF', 'image/JPG', 'image/PNG', 'image/JPEG'];
    $allowedExtensions = ['gif', 'jpg', 'jpeg', 'png', 'GIF', 'JPG', 'JPEG', 'PNG'];

    // Get file info
    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = mime_content_type($fileTmpName);
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    // Validate file type and size
    if (in_array($fileType, $allowedMimeTypes) && in_array($fileExt, $allowedExtensions) && $fileSize <= 1024 * 1024) {
        $uploadDir = 'uploads/';
        $filePath = $uploadDir . uniqid() . '.' . $fileExt;

        // Move file to upload directory
        if (move_uploaded_file($fileTmpName, $filePath)) {
            // Resize image to fit within 200x200 while maintaining aspect ratio
            list($width, $height) = getimagesize($filePath);
            $maxDim = 200;

            if ($width > $height) {
                $newWidth = $maxDim;
                $newHeight = $height * ($maxDim / $width);
            } else {
                $newHeight = $maxDim;
                $newWidth = $width * ($maxDim / $height);

            $thumb = imagecreatetruecolor($newWidth, $newHeight);

            switch ($fileType) {
                case 'image/jpeg':
                case 'image/JPEG':
                case 'image/jpg':
                case 'image/JPG':
                    $source = imagecreatefromjpeg($filePath);
                case 'image/png':
                case 'image/PNG':
                    $source = imagecreatefrompng($filePath);
                case 'image/gif':
                case 'image/GIF':
                    $source = imagecreatefromgif($filePath);
                    $source = imagecreatefromjpeg($filePath);

            imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

            switch ($fileType) {
                case 'image/jpeg':
                case 'image/JPEG':
                case 'image/jpg':
                case 'image/JPG':
                    imagejpeg($thumb, $filePath);
                case 'image/png':
                case 'image/PNG':
                    imagepng($thumb, $filePath);
                case 'image/gif':
                case 'image/GIF':
                    imagegif($thumb, $filePath);


            // Return the file URL
            echo json_encode(['url' => $filePath]);
        } else {
            echo json_encode(['error' => 'Failed to move uploaded file']);
    } else {
        echo json_encode(['error' => 'Invalid file type or size']);
} else {
    echo json_encode(['error' => 'No file uploaded']);

Notes on the PHP Script:

  • Allowed File Types: We define arrays for allowed MIME types and file extensions to ensure only valid images are processed.
  • File Info: We extract the file name, temporary name, size, MIME type, and extension.
  • Validation: We check if the file type and size are valid.
  • Upload Directory: The uploaded file is moved to the uploads/ directory.
  • Image Resizing: We resize the image to fit within a 200×200 pixel box while maintaining the aspect ratio using imagecopyresampled for better quality.
  • Return JSON: The script returns the file URL in JSON format for the Summernote editor to use.


And that’s it! You’ve successfully set up multiple Summernote editors to handle image uploads with PHP. Each uploaded image is resized to fit within a 200×200 pixel box while maintaining its aspect ratio. The image URL is then inserted back into the respective Summernote editor.

If you have any questions or run into any issues, feel free to leave a comment below. Happy coding!


Minifying JavaScript Files Using Python and jsmin

Minifying JavaScript files can significantly improve the performance of your web applications by redā€¦

Automating WordPress Updates with Python: A Step-by-Step Guide square
Automating WordPress Updates with Python: A Step-by-Step Guide

Learn how to automate updates on your WordPress site using Python and the REST API. This comprehensiā€¦

Leave a Reply

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