Create a multi-level directory in php

Source: Internet
Author: User
Tags mkdir

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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.