简体   繁体   中英

Deleting folder and files inside directory in php

I am trying to find a way of deleting a folder which is located inside another (eg accounts/username - i want to delete username but it has 2 folders inside (1 names images and other named videos) - with files inside.

I have tried

$accounts = "accounts";
$uploaddir = "$username";
$image_dir = 'image';
$video_dir = 'video';

$image_folder = "$accounts$username$image_dir/";
$uploadfile = $image_folder . basename($_FILES['image']['name']);

$dir = "$accounts/$uploaddir";
array_map('unlink', glob($dir."/*"));
rmdir($dir);

key function : unlink files , scandir and rmdir but you need to scan that directory for all its content and do accordingly

1.Unlink on case of file 2.Remove on case of Directory using is_dir() function.

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

onyour case:

$dir = "$accounts/$uploaddir";
deleteDir($dir);

Cheers!

You can use following function,

unlink(file_path);

You can remove complete folder/files. refer http://php.net/manual/en/function.unlink.php

Thanks Amit

Here is function, I use all time:

function delete_directory($dirname) {
   if (is_dir($dirname))
      $dir_handle = opendir($dirname);

   if (!$dir_handle)
      return false;
   while($file = readdir($dir_handle)) {
      if ($file != "." && $file != "..") {
         if (!is_dir($dirname."/".$file))
            unlink($dirname."/".$file);
         else
            delete_directory($dirname.'/'.$file);    
      }
   }
   closedir($dir_handle);
   rmdir($dirname);
   return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM