hey guys, i wonder what's the easiest way to delete a directory with all it's 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.
regards
hey guys, i wonder what's the easiest way to delete a directory with all it's 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.
regards
There are at least two options available nowdays.
Before deleting the folder, delete all it's 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);
}
And if you are using 5.3 you can use a RecrusiveIterator to do it without recrusion, but it may not seem so simple:
$it = new RecursiveDirectoryIterator(
'samples' . DIRECTORY_SEPARATOR . 'sampledirtree');
$files = new RecursiveIteratorIterator($it,
RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file){
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
what's the easiest way to delete a directory with all it's files in it?
system("rm -rf $dir");