I need to delete a folder with contents using PHP. rmdir()
and unlink()
delete empty folders, but are not able to delete folders which have contents.
PHP rmdir() Function The rmdir() function removes an empty directory.
To remove a directory that is not empty, use the rm command with the -r option for recursive deletion.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
This function will allow you to delete any folder (as long as it's writable) and it's files and subdirectories.
function Delete($path) { if (is_dir($path) === true) { $files = array_diff(scandir($path), array('.', '..')); foreach ($files as $file) { Delete(realpath($path) . '/' . $file); } return rmdir($path); } else if (is_file($path) === true) { return unlink($path); } return false; }
Or without recursion using RecursiveDirectoryIterator
:
function Delete($path) { if (is_dir($path) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST); foreach ($files as $file) { if (in_array($file->getBasename(), array('.', '..')) !== true) { if ($file->isDir() === true) { rmdir($file->getPathName()); } else if (($file->isFile() === true) || ($file->isLink() === true)) { unlink($file->getPathname()); } } } return rmdir($path); } else if ((is_file($path) === true) || (is_link($path) === true)) { return unlink($path); } return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With