In this article, I will explain how to delete images from the server using Summernote, a WYSIWYG editor, with the help of PHP, MySQL, jQuery, and Ajax. #Summernote is a popular open-source #WYSIWYG editor that allows users to create rich text content, including images. Sometimes, users may want to delete the images they have uploaded to the server, which requires implementing the functionality to delete images. Prerequisites: To follow along with this tutorial, you should have a basic understanding of #PHP, #MySQL, #jQuery, and #Ajax. You should also have Summernote installed on your web application.

#php #php-lessons #unlink #summernote

Step 1: Create a database table

Create a database table named "images" to store the image details. The table should have the following fields:
  • id (primary key)
  • name (the name of the image file)
  • path (the path of the image file on the server)
  • created_at (the date and time the image is uploaded)
Here's an example SQL code for creating the "images" table.  
CREATE TABLE images (
  id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  path VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
This code creates a table named "images" with four columns: "id" (an auto-incrementing primary key), "name" (the name of the image file), "path" (the path of the image file on the server), and "created_at" (the date and time the image was uploaded, set to the current timestamp by default). Note that the specific data types and column names used may vary depending on your specific requirements and database schema.

Step 2: Create a PHP script to handle the image deletion

Create a PHP script that handles the deletion of images from the server. The script should accept a parameter named "id" that corresponds to the ID of the image to be deleted.  
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');

// Check if the ID parameter is set
if(isset($_POST['id'])) {
  $id = $_POST['id'];

  // Retrieve the image details from the database
  $query = "SELECT * FROM images WHERE id = $id";
  $result = mysqli_query($conn, $query);
  $row = mysqli_fetch_assoc($result);

  // Delete the image file from the server
  unlink($row['path']);

  // Delete the image details from the database
  $query = "DELETE FROM images WHERE id = $id";
  mysqli_query($conn, $query);
}
?>
 

Step 3: Modify the Summernote initialization code

Modify the Summernote initialization code to add a custom button that deletes the selected image. The code should look like this:  
$(document).ready(function() {
  $('#summernote').summernote({
    toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'italic', 'underline', 'clear']],
      ['fontname', ['fontname']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['height', ['height']],
      ['custom', ['deleteImage']],
    ],
    buttons: {
      deleteImage: function() {
        var image = $('.note-image-input:checked').closest('.note-image-popover').find('.note-image-filename').text();
        var id = $('.note-image-input:checked').closest('.note-image-popover').data('value');
        $.ajax({
          url: 'delete-image.php',
          method: 'POST',
          data: {id: id},
          success: function() {
            $('.note-image-input:checked').closest('.note-image-popover').remove();
          }
        });
      }
    }
  });
});
  The "deleteImage" button is added to the Summernote toolbar. When the button is clicked, the code retrieves the name and ID of the selected image and sends a POST request to the "delete-image.php" script. On successful deletion of the image from the server, the code removes the image from the Summernote editor.

Step 4: Test the code

Test the code by uploading an image to the Summernote editor and then clicking on the "deleteImage" button. The image will delete from the server and removed from the database. The above code provides a basic implementation for deleting images from the server using Summernote. However, there are a few things to keep in mind when implementing this functionality in your own web application:
  1. Security considerations: Ensure that the PHP script used for deleting images has proper security measures in place to prevent unauthorized access or malicious file deletion. This may include implementing user authentication, validating user input, and sanitizing user data.
  2. File paths and naming conventions: Ensure that the file paths and naming conventions used for storing images on the server are consistent and easy to manage. It is also important to properly handle file extensions to prevent security issues such as file upload vulnerabilities.
  3. Error handling: It is important to handle errors that may occur during image deletion, such as network errors, server errors, or file permission errors. Proper error handling can improve the user experience and prevent potential security issues.
  4. Server space and performance: Keep in mind that deleting images from the server can free up disk space and improve server performance.
In summary, deleting images from the server using Summernote requires implementing the functionality to delete images using PHP, MySQL, jQuery, and Ajax. The code provided in this article provides a basic implementation and can be modified to suit your specific requirements. When implementing this functionality, it is important to consider security, file paths and naming conventions, error handling, and server space and performance. Read more on how I created a script that will delete images not in your database and optimize them at the same time.

Script To Optimize Images & delete Images Not In Database

I wrote this script so it will would tell me what images were on the server but not in the database. This was a little tricky because Summernote stores the images in HTML. Furthermore, we had to use htpmentities in order to store it in the database safely. I also made it so that it optimizes images on the server at the same time. Here is the script.
<?php error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once('config.php');
//This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImageFolder    = 'img-uploads/'; //Source Image Directory End with Slash
$MoveImgeToHere    = 'img-uploads/'; //Destination Image Directory End with Slash
$PicWidth      = 500; //New Width of Image
$PicHeight     = 500; // New Height of Image
$ImageQuality        = 80; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImageFolder)){
    while(($file = readdir($dir))!== false){
        $imagePath = $ImageFolder.$file;
        $destPath = $MoveImgeToHere.$file;
        $checkValidImage = @getimagesize($imagePath);
        if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
        {
            //Image looks valid, resize.
            if(resizeImage($imagePath,$destPath,$PicWidth,$PicHeight,$ImageQuality))
            {
                //echo $file.' resize Success!<br />';
                /*
                After Image resize save to database
                */

            }else{
                echo $file.' resize Failed!<br />';
            }
        }
    }
    closedir($dir);
}
//Function that resizes image.
function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$ImageQuality)
{
    list($iWidth,$iHeight,$type)    = getimagesize($SrcImage);
    $ImageScale             = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
    $NewWidth               = ceil($ImageScale*$iWidth);
    $NewHeight              = ceil($ImageScale*$iHeight);
    $NewCanves              = imagecreatetruecolor($NewWidth, $NewHeight);

    switch(strtolower(image_type_to_mime_type($type)))
    {
        case 'image/jpeg':
            $NewImage = imagecreatefromjpeg($SrcImage);
            break;
        case 'image/JPEG':
            $NewImage = imagecreatefromjpeg($SrcImage);
            break;
        case 'image/png':
            $NewImage = imagecreatefrompng($SrcImage);
            break;
        case 'image/PNG':
            $NewImage = imagecreatefrompng($SrcImage);
            break;
        case 'image/gif':
            $NewImage = imagecreatefromgif($SrcImage);
            break;
        default:
            return false;
    }
    // Resize Image
    if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
    {
        // copy file
        if(imagejpeg($NewCanves,$DestImage,$ImageQuality))
        {
            imagedestroy($NewCanves);
            return true;
        }
    }
}
echo '<div class="alert alert-success">Images resized</div>';
echo '<br/>';
$result = $con->query("SELECT descr FROM merch") ;
while ($row = $result->fetch_assoc()) {
  $html = html_entity_decode($row['descr']);
}
//get number of images
$pattern = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i';
$numberofimages = preg_match_all($pattern, $html);
//get image paths from html
$get_Img_Src = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i'; //get img src path only...
//$cunn=preg_match_all($get_Img_Src, $html, $result); 
preg_match_all($get_Img_Src, $html, $result); 

//delete images
for($var=0; $var < $numberofimages; $var++){
  echo $result['src'][$var];
//unlink($result['src'][$var]);
}
$result = $con->query("SELECT descr FROM merch") ;
$pattern = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i';
$get_Img_Src = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i'; //get img src path only...
$total=0;
$html='';
while ($row = $result->fetch_assoc()) {
  $html .= html_entity_decode($row['descr']);
  $numberofimages = preg_match_all($pattern, $html);
  $total=+$numberofimages;
}
preg_match_all($get_Img_Src, $html, $result); 
$array = array();
for($var=0; $var < $total; $var++){
  $array[] = substr($result['src'][$var], 14);
//unlink($result['src'][$var]);
}
echo '<pre>';
print_r($array);
echo '</pre>';
 $imagepath = 'img-uploads';
 $images = array_slice(scandir($imagepath), 2);
 echo '<pre>';
  print_r($images);
  echo '</pre>';
  
  $resultss = array_diff($images, $array);
 foreach($images as $img) 
 {
     if(!in_array($img,$array)) {
        // delete file 
        unlink('img-uploads/'.$img);
        print("Deleted file [". $img ."]\n");
      } 
 } 
  echo '<pre>';
  print_r($resultss); 
 echo '</pre>';
echo '<div class="alert alert-success">The entry and all of the images have been deleted</div>';
$con->close();
?>

Test Script To Practice With

Now you may just want to view whats going on. I created this test script that will just put out arrays so you can see what is going on. I also used this in the video that I created.
<?php include_once('config.php'); 
$result = $con->query("SELECT descr FROM merch") ;
$pattern = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i';
$get_Img_Src = '/<img[^>]*src=([\'"])(?<src>.+?)\1[^>]*>/i'; //get img src path only...
$total=0;
$html='';
while ($row = $result->fetch_assoc()) {
  $html .= html_entity_decode($row['descr']);
  $numberofimages = preg_match_all($pattern, $html);
  $total=+$numberofimages;
}
preg_match_all($get_Img_Src, $html, $result); 
$array = array();
for($var=0; $var < $total; $var++){
  $array[] = substr($result['src'][$var], 14);
//unlink($result['src'][$var]);
}
echo '<h2>Files Taken From Summernote in Database</h2>';
echo '<pre>';
print_r($array);
echo '</pre>';
 $imagepath = 'img-uploads';
 $images = array_slice(scandir($imagepath), 2);
echo '<h2>Files Taken From Image Uploads Directory</h2>';
 echo '<pre>';
  print_r($images);
  echo '</pre>';
  echo '<h2>Files Not In Database</h2>';
  $resultss = array_diff($images, $array);
 foreach($images as $img) 
 {
     if(!in_array($img,$array)) {
        // delete file 
        //unlink('img-uploads/'.$img);
        print("File not in database [". $img ."]\n");
    echo '<br/>';
      } 
 } 
  echo '<pre>';
  print_r($resultss); 
 echo '</pre>';
$con->close();
?>


Sign Up To Comment