Derek Kennedy
Derek Kennedy

Reputation: 155

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

Upvotes: 1

Views: 86

Answers (3)

Misha Akopov
Misha Akopov

Reputation: 13057

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;
}

Upvotes: 0

Daniel Wondyifraw
Daniel Wondyifraw

Reputation: 7723

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!

Upvotes: 1

Amit Shah
Amit Shah

Reputation: 1380

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

Upvotes: 1

Related Questions