开发者

Create file and folders recursively

I got an array containing path names and file names

['css/demo/main.css', 'home.css', 'admin/main.css','account']

I want to create those files and folders if they are not existed yet. Overwrite them if they are already existed.开发者_运维技巧


For each of this paths you'll have to specific whether it is a file or a directory. Or you could make your script assume, that the path is pointing to a file when the basename (the last part of the path) contains a dot.

To create a directory recursively is simple:

mkdir(dirname($path), 0755, true); // $path is a file
mkdir($path, 0755, true);          // $path is a directory

0755 is the file permission expression, you can read about it here: http://ch.php.net/manual/en/function.chmod.php


<?php
  function mkpath($path)
  {
    if(@mkdir($path) or file_exists($path)) return true;
    return (mkpath(dirname($path)) and mkdir($path));
  }
?>

This makes paths recursively.


I have just used a simple way to explode the string and rebuild and check if is a file or a directory

public function mkdirRecursive($path) {


    $str = explode(DIRECTORY_SEPARATOR, $path);
    $dir = '';
    foreach ($str as $part) {
        $dir .= DIRECTORY_SEPARATOR. $part ;
        if (!is_dir($dir) && strlen($dir) > 0 && strpos($dir, ".") == false) {
            mkdir($dir , 655);
        }elseif(!file_exists($dir) && strpos($dir, ".") !== false){
           touch($dir);
        }
    }
}


You can use is_dir

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜