What is the correct method to delete a directory with content in PHP?
When deleting a directory with content in PHP, you need to recursively delete all files and subdirectories within the directory before removing the directory itself. This ensures that all contents are properly removed and prevents any potential errors.
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
deleteDirectory('/path/to/directory');