Hongmu Notes
Home Language Notes PHP checks whether a specified directory contains a directory with a given prefix; if such a directory exists, it returns the directory name; otherwise, it creates a new directory.
Language Notes PHP

PHP checks whether a specified directory contains a directory with a given prefix; if such a directory exists, it returns the directory name; otherwise, it creates a new directory.

PHP checks whether a specified directory contains a directory with a given prefix; if such a directory exists, it returns the directory name; otherwise, it creates a new directory.

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;
}

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(PC+WAP) – Construction Structural Engineering Website pbootCMS Template; Air-supported Structure Website Source Code Download – 0044

(PC+WAP) – Construction Structural Engineering Website pbootCMS Template; Air-supported Structure Website Source Code Download – 0044 Practical Collection pbootcms Template

A PbootCMS website template designed for the architectural structural engineering and air-supported structure construction industries, compatible with both PC and WAP devices. Its modern, minimalist design effectively showcases the aesthetic appeal and technical expertise of building projects. The template includes built-in modules for project displays, technical analyses, and industry news, helping construction companies establish a professional online presence. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: a...
👁 66
(Adaptive Mobile Version) Responsive Marketing Technology – Personal Blog Website Template 0965

(Adaptive Mobile Version) Responsive Marketing Technology – Personal Blog Website Template 0965 Practical Collection pbootcms Template

A responsive marketing technology-themed personal blog template (PbootCMS), compatible with both PC and WAP devices. Its professional, tech-oriented design makes it ideal for technical professionals to share marketing strategies, SEO knowledge, and industry insights. This template helps tech bloggers build their personal brand and online influence. Template Preview | Installation Instructions | Website Admin Panel: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 38
Water Supply Dispatch System Website Template 0738

Water Supply Dispatch System Website Template 0738 Practical Collection Yiyou template

An eYouCMS website template designed for enterprises specializing in water supply dispatching systems. Its modern, technology-driven design is ideal for showcasing water supply dispatching systems, water utility management solutions, technical proposals, and project cases. This template helps water utilities and technology-based companies present their products online and attract municipal clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYou...
👁 34
(PC+WAP) Energy-efficient building shading products – Marketing-oriented website using PBootCMS template; Energy-saving building websites source code download – 0045

(PC+WAP) Energy-efficient building shading products – Marketing-oriented website using PBootCMS template; Energy-saving building websites source code download – 0045 Practical Collection pbootcms Template

This PbootCMS template is designed as a marketing-oriented corporate website for building energy efficiency and shading product companies, supporting both PC and mobile devices. The clean, eco-friendly design emphasizes the principles of energy conservation and environmental sustainability. The pages highlight shading products, energy-saving solutions, and project cases, enabling building energy efficiency firms to efficiently acquire online customers and showcase their technical advantages. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 39