How can one efficiently handle the deletion of directories with files in PHP to avoid errors or issues?
When deleting directories with files in PHP, it's important to first delete all files within the directory before attempting to remove the directory itself. This can be achieved by using functions like `scandir()` to get a list of files in the directory, then iterating over them to delete each file individually. Once all files are deleted, the directory can be removed using `rmdir()`.
function deleteDirectory($dir) {
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
if (is_dir($path)) {
deleteDirectory($path);
} else {
unlink($path);
}
}
rmdir($dir);
}
// Example usage:
$directoryToDelete = 'path/to/directory';
deleteDirectory($directoryToDelete);