Delete Images Off Server In Summernote with php, mysql, jquery, and ajax

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();
?>

Delete Images Off Server In Summernote with php, mysql, jquery, and ajax was last modified: February 25th, 2023 by Maximus Mccullough
Summary
Delete Images Off Server In Summernote with php, mysql, jquery, and ajax
Article Name
Delete Images Off Server In Summernote with php, mysql, jquery, and ajax
Description
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.
Author
Publisher
A1WEBSITEPRO LLC
Logo
Delete Images Off Server In Summernote with php, mysql, jquery, and ajax

Pages:Previous 1 2

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.