Encapsulated code:
隐藏内容:登录后可查看
function checkOrCreateDirectory($dir, $prefix, $newDirName) {
$directories = array_filter(glob($dir . '/*'), 'is_dir');
foreach ($directories as $directory) {
$directoryName = basename($directory);
if (strpos($directoryName, $prefix) === 0) {
return $directoryName;
}
}
$newDirectory = $dir . '/' . $prefix . $newDirName;
if (!file_exists($newDirectory)) {
mkdir($newDirectory, 0777, true);
}
return $prefix . $newDirName;
}
This function accepts three parameters: the directory name to be checked, the prefix to be checked, and the name of the new directory to be created. It will use glob() The function retrieves all subdirectories from the directory and uses them. array_filter() The function filters out all non-directory files. Then, it iterates through all directories and checks whether their names start with the specified prefix. If a matching directory is found, the function immediately returns its name; otherwise, it creates a new directory and returns its name.
Note: This function is being used. file_exists() Use a function to check whether a new directory already exists, thereby preventing the duplicate creation of a directory with the same name. If you wish to apply different access permissions when creating a new directory, you can modify the relevant settings. mkdir() The third parameter of the function.
Function with properly annotated comments
隐藏内容:会员可查看
/**
* 检查指定目录是否存在前缀admin-的目录,如果存在便返回目录名称,不存在则创建一个目录。
* @param string $dir 需要检查的目录名。
* @param string $prefix 需要检查的前缀。
* @param string $newDirName 要创建的新目录名。
* @return string 返回目录名称。
*/
function checkOrCreateDirectory($dir, $prefix, $newDirName) {
// 使用 glob() 函数获取目录中的所有子目录。
$directories = array_filter(glob($dir . '/*'), 'is_dir');
// 循环遍历所有目录。
foreach ($directories as $directory) {
// 使用 basename() 函数获取目录名称。
$directoryName = basename($directory);
// 检查目录名称是否以指定的前缀开头。
if (strpos($directoryName, $prefix) === 0) {
// 如果找到匹配的目录,立即返回目录名称。
return $directoryName;
}
}
// 如果没有找到匹配的目录,创建新目录。
$newDirectory = $dir . '/' . $prefix . $newDirName;
// 检查新目录是否已经存在,如果不存在则创建目录。
if (!file_exists($newDirectory)) {
// 使用 mkdir() 函数创建新目录。
mkdir($newDirectory, 0777, true);
}
// 返回新目录名称。
return $prefix . $newDirName;
}