Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete directory with files in it?

Tags:

php

rmdir

I wonder, what's the easiest way to delete a directory with all its files in it?

I'm using rmdir(PATH . '/' . $value); to delete a folder, however, if there are files inside of it, I simply can't delete it.

like image 254
matt Avatar asked Jul 28 '10 03:07

matt


People also ask

Can you delete a directory with files in Linux?

You can delete a directory in Linux using the rm command. The rm command can delete a directory if it contains files as long as you use the -r flag. If a directory is empty, you can delete it using the rm or rmdir commands.

How do I delete a directory that is not empty in Terminal?

To remove a directory that is not empty, use the rm command with the -r option for recursive deletion. Be very careful with this command, because using the rm -r command will delete not only everything in the named directory, but also everything in its subdirectories.

How do I delete files from a directory?

Open My Computer or Windows Explorer. Locate and select the file or folder you want to delete, click File in the top menu bar, and select Delete.


2 Answers

There are at least two options available nowadays.

  1. Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:

    public static function deleteDir($dirPath) {     if (! is_dir($dirPath)) {         throw new InvalidArgumentException("$dirPath must be a directory");     }     if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {         $dirPath .= '/';     }     $files = glob($dirPath . '*', GLOB_MARK);     foreach ($files as $file) {         if (is_dir($file)) {             self::deleteDir($file);         } else {             unlink($file);         }     }     rmdir($dirPath); } 
  2. And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself:

    $dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree'; $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it,              RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) {     if ($file->isDir()){         rmdir($file->getRealPath());     } else {         unlink($file->getRealPath());     } } rmdir($dir); 
like image 80
alcuadrado Avatar answered Oct 20 '22 23:10

alcuadrado


I generally use this to delete all files in a folder:

array_map('unlink', glob("$dirname/*.*")); 

And then you can do

rmdir($dirname); 
like image 41
user3033886 Avatar answered Oct 20 '22 22:10

user3033886