Update the recursive_delete function

- Use opendir instead of glob for better performance
- Use native PHP code for safe recursive delete
- Remove command line exec
This commit is contained in:
FusionPBX
2026-02-26 06:38:25 -07:00
committed by GitHub
parent 8ea7a74dad
commit 148d032e36

View File

@@ -352,56 +352,55 @@ if (!function_exists('recursive_copy')) {
}
if (!function_exists('recursive_delete')) {
if (file_exists('/usr/bin/find')) {
/**
* Recursively deletes all files and directories within the given directory.
*
* @param string $directory The directory path to delete files from.
*
* @return void This function does not return a value.
*/
function recursive_delete($directory) {
if (isset($directory) && strlen($directory) > 8) {
exec('/usr/bin/find ' . $directory . '/* -name "*" -delete');
//exec('rm -Rf '.$directory.'/*');
clearstatcache();
/**
* Safely deletes a directory and all its contents recursively
*
* @param string $path The path to the directory to delete
* @return bool True on success, false on failure
*/
function recursive_delete($path) {
// Verify the path exists and is a directory
if (!file_exists($path) || !is_dir($path)) {
return false;
}
// Prepare the directory handle
$handle = opendir($path);
// No handle, send a return
if (!$handle) return;
// Loop through all files and subdirectories
while (false !== ($file = readdir($handle))) {
// Skip '.' and '..' as they refer to the current and parent directory
if ($file == '.' || $file == '..') {
continue;
}
}
} elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
/**
* Recursively deletes the given directory and all its contents.
*
* @param string $directory The directory to delete. If the path is not normalized, it will be converted using normalize_path_to_os().
*
* @return bool True if the deletion was successful, false otherwise.
*/
function recursive_delete($directory) {
$directory = normalize_path_to_os($directory);
//$this->write_debug("del /S /F /Q \"$dir\"");
exec("del /S /F /Q \"$directory\"");
clearstatcache();
}
} else {
/**
* Recursively deletes files and directories in the given directory.
*
* @param string $directory The path to the directory containing files/directories to delete.
*
* @return bool True if all files/directories were successfully deleted, false otherwise.
*/
function recursive_delete($directory) {
foreach (glob($directory) as $file) {
if (is_dir($file)) {
//$this->write_debug("rm dir: ".$file);
recursive_delete("$file/*");
rmdir($file);
} else {
//$this->write_debug("delete file: ".$file);
unlink($file);
// Set the full path
$full_path = $path . DIRECTORY_SEPARATOR . $file;
// If this is a directory, recursively delete it
if (is_dir($full_path)) {
if (!recursive_delete($full_path)) {
closedir($handle);
return false;
}
}
else {
// If this is a file, delete it
if (!unlink($full_path)) {
closedir($handle);
return false;
}
}
clearstatcache();
}
// Close the directory handle
closedir($handle);
// Remove the now-empty directory
return rmdir($path);
}
}