Write a PHP function that checks whether a specified directory contains a subdirectory with the prefix "admin-"; if such a directory exists, return its name; otherwise, create a new directory. The variable `admin-` represents the prefix, and the second argument is the name of the new directory to be created.
Here is a PHP function that implements this functionality. The function first checks whether there is a directory in the specified directory that starts with "admin-"; if such a directory exists, it returns its name; otherwise, it creates a new directory and returns the name of that new directory.
The first parameter of this function is the directory path to be checked; the second parameter is the name of the new directory to be created. Within the function, we use opendir() 和 readdir() The function iterates through all files and subdirectories within a specified directory. If a directory with the prefix "admin-" is found, the function will utilize it. closedir() The function closes the directory handle and returns the directory name. If no directory with the prefix "admin-" is found, the function will use... mkdir() The function creates a new directory and returns the name of the new directory.
Here is an example of usage:
$dir = '/path/to/directory';
$admin_dir_name = 'admin-';
$new_dir_name = 'admin-JUSKD';
$result = check_admin_dir($dir, $new_dir_name);
if ($result === false) {
echo 'Failed to create directory.';
} else if ($result === $new_dir_name) {
echo 'Created new directory: ' . $result;
} else {
echo 'Found existing directory: ' . $result;
}In the above example, we first define the directory path to be checked and the name of the new directory to be created. Then, we call check_admin_dir() Call the function and pass these two parameters to it. Finally, check the result returned by the function and output the corresponding message based on that result. If the function returns falseIf the function returns `NULL`, it indicates that the directory creation failed; if the function returns a new directory name, it indicates that the new directory was successfully created; if the function returns the name of an existing directory, it indicates that an existing directory was found.