Last active
October 7, 2023 11:10
-
-
Save nagiyevelchin/0cb920b313fab2660d0c8a003e48937e to your computer and use it in GitHub Desktop.
Efficient PHP Function for Deleting Directories and Their Contents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Efficient PHP Function for Deleting Directories and Their Contents | |
* | |
* This PHP function, named 'deleteDirectory,' is designed to safely and | |
* efficiently delete directories and all their contents. It first checks if | |
* the directory exists, and if not, it returns 'true' since the directory is | |
* already deleted. Next, it determines whether the specified path is a directory | |
* or a symbolic link and unlinks it if necessary. | |
* | |
* The function then recursively scans and deletes all items within the directory, | |
* handling subdirectories and files alike. In case an item cannot be deleted on | |
* the first attempt, it adjusts permissions and retries the deletion. If all | |
* contents are successfully deleted, the function proceeds to remove the directory itself. | |
* | |
* This well-documented and versatile PHP code is a valuable tool for managing | |
* file systems and ensuring the secure removal of directories and their contents. | |
*/ | |
function deleteDirectory($dir) { | |
// Check if the directory does not exist, then it's already deleted | |
if (!file_exists($dir)) { | |
return true; | |
} | |
// Check if $dir is not a directory or is a symbolic link, and unlink it if true | |
if (!is_dir($dir) || is_link($dir)) { | |
return unlink($dir); | |
} | |
// Iterate through the contents of the directory | |
foreach (scandir($dir) as $item) { | |
// Skip the special directories "." and ".." | |
if ($item == '.' || $item == '..') { | |
continue; | |
} | |
// Recursive call to deleteDirectory for subdirectories and files | |
if (!self::deleteDirectory($dir . "/" . $item)) { | |
// If deletion fails, change permissions and attempt deletion again | |
@chmod($dir . "/" . $item, 0777); | |
if (!deleteDirectory($dir . "/" . $item)) { | |
// Return false if unable to delete an item | |
return false; | |
} | |
} | |
} | |
// Finally, remove the directory itself | |
return rmdir($dir); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment