You can use PHP's built-in functions. file_exists() 和 is_dir() Check whether the directory exists. If it exists, you can use it. glob() The function retrieves all files in the directory and uses them. unlink() The function removes them. If the directory does not exist, it can be used. mkdir() Create a directory.
Here is an example code that implements the aforementioned functionality:
$dir = '/path/to/directory'; // 目录路径
if (file_exists($dir) && is_dir($dir)) {
// 目录已存在,清空目录
$files = glob($dir . '/*'); // 获取目录下的所有文件
foreach ($files as $file) {
if (is_file($file)) {
unlink($file); // 删除文件
}
}
} else {
// 目录不存在,创建目录
mkdir($dir, 0777, true); // 创建目录
}In this example,$dir The path to the variable storage directory. Use this first. file_exists() 和 is_dir() Check whether the directory exists. If the directory exists, proceed. glob() The function retrieves all files in the directory and uses them. unlink() The function removes them. If the directory does not exist, use it. mkdir() The function creates a directory. mkdir() The second parameter in the function 0777 Specifies that all users are granted read, write, and execute permissions for the directory. The third parameter true This function recursively creates a directory; if the parent directory does not exist, it will also be created.
Encapsulating the above code into a function makes it more reusable and maintainable; below is an example of such encapsulation:
The parameter of this function is the path to the directory to be manipulated. When the function is called, it checks whether the directory exists; if it does, the directory is emptied; if it does not, the directory is created. You can call this function as follows:
clearOrCreateDirectory('/path/to/directory');among /path/to/directory The path to the directory to be operated on.