What are the implications of deleting directories within a PHP script and how can it be done safely?
Deleting directories within a PHP script can have serious implications if not done carefully. To safely delete directories in PHP, you should first check if the directory exists and if it is safe to delete. You should also ensure that the directory is not a system directory or a critical folder. Additionally, you should recursively delete all files and subdirectories within the directory before removing the directory itself.
<?php
function deleteDirectory($dir) {
if (!file_exists($dir) || !is_dir($dir)) {
return false;
}
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
if (is_dir($path)) {
deleteDirectory($path);
} else {
unlink($path);
}
}
return rmdir($dir);
}
// Example usage
$directoryToDelete = 'path/to/directory';
if (deleteDirectory($directoryToDelete)) {
echo 'Directory deleted successfully.';
} else {
echo 'Failed to delete directory.';
}
?>