Create a multi-level directory in php

Source: Internet
Author: User

Example

The code is as follows: Copy code

Function mkdirs ($ dir ){
If (! Is_dir ($ dir )){
If (! Mkdirs (dirname ($ dir ))){
Return FALSE;
        }

If (! Mkdir ($ dir, 0777 )){
Return FALSE;
        }
    }

Return TRUE;
}

$ Path = "/aa/bb/cc/cd"; // directory to be created
$ Mode = 0755; // directory creation mode
Createdir ($ path, $ mode); // Test

The function used by php to create a directory is mkdir ($ dir, $ mode). However, it can only create one directory at a time. That is to say, it cannot create a multi-level directory at a time (you must know this, here, let's make up one more ).

I have compiled two methods for recursively creating directories for your reference. Thank you!

The code is as follows: Copy code

<? Php
/*
* Mkdir ($ dir, $ mode)
* Recursive directory creation in PHP
*/
Function mkdirs ($ dir, $ mode = 0777)
{
If (is_dir ($ dir) | @ mkdir ($ dir, $ mode )){
Return true;
    }
If (! Mkdirs (dirname ($ dir), $ mode )){
Return false;
    }
Return @ mkdir ($ dir, $ mode );
}

Function mkdirs ($ dir, $ mode = 0777)
{
$ DirArray = explode ("/", $ dir );
$ DirArray = array_filter ($ dirArray );
  
$ Created = "";
Foreach ($ dirArray as $ key => $ value ){
If (! Empty ($ created )){
$ Created. = "/". $ value;
If (! Is_dir ($ created )){
Mkdir ($ created, $ mode );
            }
} Else {
If (! Is_dir ($ value )){
Mkdir ($ value, $ mode );
            }
$ Created. = $ value;
        }
    }
}
?>
// Code application instance
$ Path = "abc/ff/ss /";
Mkdirs ($ path, $ mode = 0777 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.