Create files 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 these files and folders if they do not already exist. Overwrite them if they already exist.

+6
source share
4 answers

For each of these paths, you will need to indicate whether it is a file or a directory. Or you can make your script suppose the path points to a file when the base name (the last part of the path) contains a period.

To create a directory is recursively simple:

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

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

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

This makes the path recursive.

+2
source

I just used an easy way to blow up a line and rebuild and check if the file or directory is

 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); } } } 
0
source

Finally, I got this method and it works great for me.

 shell_exec("mkdir -p ".$your_path); 
-2
source

Source: https://habr.com/ru/post/892493/


All Articles