开发者

PHP create nested directories

I need help with a function to create a 2 level directory for the following situations:

  1. The desired sub-directory exists in the parent directory, do nothing.
  2. Parent directory exists, sub-directory does not exist. Create only the sub-directory.
  3. Neither parent directory, nor the sub-directory exists, First creat开发者_JAVA百科e parent directory, then sub-directory.
  4. If Any of the directory was not created successfully, return FALSE.

Thanks for the help.


Use the third parameter of mkdir():

recursive Allows the creation of nested directories specified in the pathname. Defaults to FALSE.

$path = '/path/to/folder/with/subdirectory';
mkdir($path, 0777, true);


recursive Allows the creation of nested directories specified in the pathname. but did not work for me!! for that here is what i came up with!! and it work very perfect!!

$upPath = "../uploads/RS/2014/BOI/002";   // full path 
$tags = explode('/' ,$upPath);            // explode the full path
$mkDir = "";

    foreach($tags as $folder) {          
        $mkDir = $mkDir . $folder ."/";   // make one directory join one other for the nest directory to make
        echo '"'.$mkDir.'"<br/>';         // this will show the directory created each time
        if(!is_dir($mkDir)) {             // check if directory exist or not
          mkdir($mkDir, 0777);            // if not exist then make the directory
        }
    }


you can try using file_exists to check if a folder exists or not and is_dir to check if it is a folder or not.

 if(file_exists($dir) && is_dir($dir))

And to create a directory you can use the mkdir function

Then the rest of your question is just manipulating this to suit the requirements


See mkdir, in particular the $recursive parameter.


How much i suffered.. and got this script..

function recursive_mkdir($dest, $permissions=0755, $create=true){
    if(!is_dir(dirname($dest))){ recursive_mkdir(dirname($dest), $permissions, $create); }  
    elseif(!is_dir($dest)){ mkdir($dest, $permissions, $create); }
    else{return true;}
}


Starting with PHP 8 (2020-11-24), you can use named parameters:

<?php
mkdir('March/April', recursive: true);

https://php.net/function.mkdir


The function you're looking for is MKDIR. Use the last parameter to recursively create directories. And read the documentation.


As of PHP 5.0+ mkdir has a recursive parameter which will create any missing parents.


// Desired folder structure
$structure = './depth1/depth2/depth3/';

// To create the nested structure, the $recursive parameter 
// to mkdir() must be specified.

if (!mkdir($structure, 0744, true)) {
    die('Failed to create folders...');
}

Returns TRUE on success or FALSE on failure.

PHP: mkdir - Manual


You can use is_dir and mkdir

if (!is_dir($path)) 
{
    @mkdir($path, 0777, true);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜