PHP can be used.glob()The function searches for all files in the current directory and then uses a loop to check, one by one, whether each file name should be deleted.unlink()The function removes unnecessary files.
Here is sample code:
<?php
$files = glob("*"); // 查找当前目录下的所有文件
foreach($files as $file) {
if(is_file($file) && $file != "1.php" && $file != "2.php") {
unlink($file); // 删除不需要的文件
}
}
?>This code is used first.glob("*")The function retrieves all files in the current directory and then uses a loop to check, one by one, whether each file name should be deleted.is_file()This function determines whether the current item is a file.$file != "1.php" && $file != "2.php"Used to determine whether the current file should be retained. If the current file does not need to be retained, then use it.unlink()The function deletes this file. Note:unlink()The function will delete files directly; therefore, use it with caution.
There are other directories in the current directory.
If there are additional directories within the current directory, recursively process these subdirectories to ensure that all unnecessary files are deleted.
Here is sample code:
This code defines a variable nameddeleteFiles()A function that accepts a single parameter.$dirIndicates the directory where the file should be deleted. The function is used first.glob("$dir/*")The function retrieves all files and directories in the current directory, then uses a loop to check, one by one, whether each file name should be deleted. If the current item is a file and is not one that should be retained, then...unlink()The function removes this file. If the current item is a directory, it will be processed recursively.deleteFiles()The function processes this directory.
Finally, use.deleteFiles(".")The function call removes all files and subdirectories in the current directory, except for 1.php and 2.php.