In php, the mkdir function recursively creates a directory (folder)

Source: Internet
Author: User

Example

The code is as follows: Copy code

<? Php
/**
* Makes directory and returns BOOL (TRUE) if exists OR made.
 *
* @ Param $ path Path name
* @ Return bool
*/
Function rmkdir ($ path, $ mode = 0755 ){
$ Path = rtrim (preg_replace (array ("/\/", "// {2,}/"), "/", $ path ),"/");
$ E = explode ("/", ltrim ($ path ,"/"));
If (substr ($ path, 0, 1) = "/"){
$ E [0] = "/". $ e [0];
    }
$ C = count ($ e );
$ Cp = $ e [0];
For ($ I = 1; $ I <$ c; $ I ++ ){
If (! Is_dir ($ cp )&&! @ Mkdir ($ cp, $ mode )){
Return false;
        }
$ Cp. = "/". $ e [$ I];
    }
Return @ mkdir ($ path, $ mode );
}

?>

Example 2

Somehow the recursive version of mkdir didn't work for me on Mac and the workaraounds listed

Below alsow didn't work for me, so heres my solution:

The code is as follows: Copy code

<? Php
Function mkdir_r ($ dirName, $ rights = 0777 ){
$ Dirs = explode ('/', $ dirName );
$ Dir = '';
Foreach ($ dirs as $ part ){
$ Dir. = $ part .'/';
If (! Is_dir ($ dir) & strlen ($ dir)> 0)
Mkdir ($ dir, $ rights );
    }
}
?>

Tested and works ;)


Example 3

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;

    }

Function rmdirs ($ dir)

    {

$ D = dir ($ dir );

While (false! ==( $ Child = $ d-> read ())){

If ($ child! = '.' & $ Child! = '..'){

If (is_dir ($ dir. '/'. $ child ))

Rmdirs ($ dir. '/'. $ child );

Else unlink ($ dir. '/'. $ child );

            }

        }

$ D-> close ();

Rmdir ($ dir );

    }


The three functions that create directories all have their own advantages. I didn't test them one by one here, but I only used the second one and I felt very good.

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.