How to Handle Image Uploads in Summernote with PHP

How to Handle Image Uploads in Summernote with PHP

To integrate image uploads in Summernote using PHP, begin by setting up multiple Summernote editors on your webpage. This configuration enables users to input and format text while conveniently uploading images. You can include the necessary JavaScript and CSS for Summernote in your HTML file to get started. Once the editors are in place, focus on implementing a PHP script that handles the image uploads. This script will receive the uploaded files and store them in a designated directory on your server.

After handling the upload, it’s crucial to ensure that any uploaded images are resized to fit within a 200×200 pixel box while maintaining their aspect ratio. This can be achieved using PHP’s GD library or ImageMagick, which allows you to resize images dynamically. By following these steps, you’ll optimize your images for better performance, enhance user experience, and ensure that your Summernote editors remain visually appealing and functional.


Table of Contents


Explore the JavaScript How-To Archive for a treasure trove of tutorials and guides, from core concepts to advanced techniques. Dive in today and elevate your coding expertise!

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">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Summernote Multiple Editors</title>
    <!-- Summernote CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.css" rel="stylesheet">
    <!-- Bootstrap CSS -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <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>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <!-- Summernote JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote-bs4.min.js"></script>

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

            $('#talkpoints').summernote(config);
            $('#company_profile').summernote(config);
            $('#executive_profile').summernote(config);
            $('#event_description').summernote(config);
            $('#presenceinph').summernote(config);
            $('#othertopicsfordiscussion').summernote(config);
        });

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

            $.ajax({
                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);
                }
            });
        }
    </script>
</body>
</html>

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.

<?php
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);
                    break;
                case 'image/png':
                case 'image/PNG':
                    $source = imagecreatefrompng($filePath);
                    break;
                case 'image/gif':
                case 'image/GIF':
                    $source = imagecreatefromgif($filePath);
                    break;
                default:
                    $source = imagecreatefromjpeg($filePath);
                    break;
            }

            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);
                    break;
                case 'image/png':
                case 'image/PNG':
                    imagepng($thumb, $filePath);
                    break;
                case 'image/gif':
                case 'image/GIF':
                    imagegif($thumb, $filePath);
                    break;
            }

            imagedestroy($thumb);
            imagedestroy($source);

            // 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.

Conclusion

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!

References

2 thoughts on “How to Handle Image Uploads in Summernote with PHP

Leave a Reply

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