I really cried!
After a lot of troubleshooting, I realized that the `glob` function was somewhat tricky to use – I couldn't retrieve the system's hidden files. After much effort, I discovered that there were other functions available for querying all files!
The `PHP` function `rm` removes all files and directories within a specified directory; it accepts two parameters: the directory to be deleted and an array of files that should not be deleted.
function deleteDirectory($directory, $excludes = []) {
// 判断目录是否存在
if (!is_dir($directory)) {
throw new Exception("目录 $directory 不存在");
}
// 获取目录中的所有文件和目录
$files = array_diff(scandir($directory), ['.', '..']);
// 遍历所有文件和目录
foreach ($files as $file) {
$path = $directory . DIRECTORY_SEPARATOR . $file;
// 如果是目录,递归处理子目录
if (is_dir($path)) {
deleteDirectory($path, $excludes);
rmdir($path);
}
// 如果是文件,并且不在不需要删除的文件列表中,就删除文件
elseif (is_file($path) && !in_array($file, $excludes)) {
unlink($path);
}
}
}This function has two parameters:$directory The directory to be deleted.$excludes The list of files that should not be deleted is an array. If the directory to be deleted does not exist, the function will throw an exception.
The function is used first. scandir The function retrieves all files and directories from the directory and uses them. array_diff Remove function . 和 ..This generates an array containing only file and directory names. Then, iterate through all files and directories; if a directory is encountered, recursively call the function itself to process the subdirectories and use it. rmdir Delete empty directories; if the item is a file and is not present in the list of files to be deleted, then proceed. unlink The function deletes a file.
Call Method
// 删除 /path/to/directory 目录下的所有文件和目录,但不删除 1.php 和 2.php
$directory = '/path/to/directory';
$excludes = ['1.php', '2.php'];
deleteDirectory($directory, $excludes);