search
HomeBackend DevelopmentPHP TutorialPHP recursively creates multi-level directories, php recursive_PHP tutorial

PHP recursively creates multi-level directories, php recursively

My first feeling is to use recursion to create, the specific idea is as follows:

function Directory($dir){
    if(is_dir($dir) || @mkdir($dir,0777)){ //查看目录是否已经存在或尝试创建,加一个@抑制符号是因为第一次创建失败,会报一个“父目录不存在”的警告。

        echo $dir."创建成功<br>";  //输出创建成功的目录

    }else{

        $dirArr=explode('/',$dir); //当子目录没创建成功时,试图创建父目录,用explode()函数以'/'分隔符切割成一个数组
        array_pop($dirArr); //将数组中的最后一项(即子目录)弹出来,
        $newDir=implode('/',$dirArr); //重新组合成一个文件夹字符串
        Directory($newDir); //试图创建父目录
        if(@mkdir($dir,0777)){
            echo $dir."创建成功<br>";

        } //再次试图创建子目录,成功输出目录名
    }
}

Directory("A/B/C/D/E/F");

The output result is as shown below:

But you can see that it is too troublesome to write. Looking at the file functions in the manual, I saw a dirname() function , whose prototype is as follows:

string dirname ( string $path )

Given a string containing the full path to a file, this function returns the directory name after removing the file name.

In Windows, both slash (/) and backslash () can be used as directory separators. In other circumstances it is a slash (/).

Can be slightly optimized:

function Directory($dir){

    if(is_dir($dir) || @mkdir($dir,0777)){ 

        echo $dir."创建成功<br>";  

    }else{

        Directory(dirname($dir));

        if(@mkdir($dir,0777)){

            echo $dir."创建成功<br>";

        }

    }

}

The effect is the same.
After that, I searched for answers on the Internet and found an that was extremely insightful:

function Directory( $dir ){  

   return  is_dir ( $dir ) or Directory(dirname( $dir )) and  mkdir ( $dir , 0777);

}

Now let’s explain the whole function:

First introduce the priority order of logical operators in PHP : && > || > and > or , that is, symbolic type > letter type, AND type >OR type, so the function body can be seen as:

is_dir ( $dir ) or (Directory(dirname( $dir )) and mkdir ( $dir , 0777));

First determine whether the target directory exists. If it exists, depending on the short-circuit characteristics of or, the entire following will be short-circuited and execution will be skipped; if the target directory does not exist, the following function body will be executed:

Directory(dirname( $dir )) and mkdir ( $dir , 0777)

I thought about itThe purpose of performing recursion first: Execute recursion first to confirm that its parent directory (dirname($dir)) has been created so that the subsequent mkdir() function will not Warn when creating a subdirectory that the parent directory cannot be found.

After entering the depth of the recursion, confirm that the deepest root directory exists, and then create directories from the root directory downwards.

Finally, I suggest those who are looking for a job to go online and find some interview questions from large companies to do. After all, their exams are more comprehensive and in-depth. When learning knowledge, you should also brush up on the questions, and you must also do it. , because it’s easy to have too much ambition but too little. I optimized the function at the beginning several times before it could be used normally.

This is an interview question about recursively creating multi-level directories in PHP. In the future, the editor will find some interesting interview questions to share with you.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1068826.htmlTechArticlePHP recursively creates multi-level directories. My first impression of php recursion is to use recursive creation. The specific ideas are as follows: function Directory($dir){ if(is_dir($dir) || @mkdir($dir,0777)){ //View directory...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools