Search code examples
phpmysqlurldelete-fileunlink

How to extract folder name from mysql url and delete it with all content?


How to get image folder -> subfolder name -> from MySQL URL:

images/5d049d4ac96e6/image.jpg

and delete it with all content. At the moment code delete image.jpg file only from image subdirectory but what I need is to delete also subfolder /5d049d4ac96e6/

$stmt = $db->prepare('SELECT postImage FROM blog_posts_seo WHERE postID = :postID') ;
    $stmt->execute(array(':postID' => $_GET['delpost']));
    while($row = $stmt->fetch()){
    $delImage =  dirname(__FILE__, 2) . '/'.$row['postImage'];
    unlink($delImage);
    //rmdir(?????);
    }

How to extract this part of mysql url: /5d049d4ac96e6/


Solution

  • Before deleting the folder, delete all it's files and folders. Here is the function for that use it in while loop

    function rrmdir($dir) {
      if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
          if ($object != "." && $object != "..") {
            if (filetype($dir."/".$object) == "dir") 
               rrmdir($dir."/".$object); 
            else unlink   ($dir."/".$object);
          }
        }
        reset($objects);
        rmdir($dir);
      }
    }
    

    In your while loop

    while($row = $stmt->fetch()){
        $dir = dirname($row['postImage']).'/';
        rrmdir($dir);
    }