What is the best practice for deleting a directory in PHP?
When deleting a directory in PHP, it is important to ensure that the directory is empty before attempting to remove it. This can be achieved by recursively deleting all files and subdirectories within the directory before removing the directory itself. Using the `rmdir()` function in PHP will only work if the directory is empty, so a recursive approach is necessary.
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
// Usage
$directoryToDelete = 'path/to/directory';
deleteDirectory($directoryToDelete);