How to make directory within directory by php loop?

随声附和 提交于 2019-12-04 07:11:55

问题


How to make directory within directory by php loop?
Example: http://site_name/a/b/c/d
First create a then b within a then c within b then ....
Problem is here a,b,c,d all the folders created in root directory not one within one. Here is my code -

<?php
 $url = "http://site_name/a/b/c/d";

 $details1 = parse_url(dirname($url));

 $base_url = $details1['scheme'] . "//" . $details1['host'] . "/";

 if ($details1['host'] == 'localhost') {
    $path_init = 2;
 }else {
    $path_init = 1;
 }

 $paths = explode("/", $details1['path']);

 for ($i = $path_init; $i < count($paths); $i++) {

   $new_dir = '';
   $base_url = $base_url . $paths[$i] . "/";
   $new_dir = $base_url;
    if (FALSE === ($new_dir = folder_exist($paths[$i]))) {
      umask(0777);
       mkdir($new_dir . $paths[$i], 0777, TRUE);

  }
 }
function folder_exist($folder)
{
  // Get canonicalized absolute pathname
    $path = realpath($folder);

  // If it exist, check if it's a directory
  return ($path !== false AND is_dir($path)) ? $path : false;
}

 ?>

回答1:


please check this code. it will create nested folder if not exit

<?php
 $your_path = "Bashar/abc/def/ghi/dfsdfds/get_dir.php";
 $array_folder = explode('/', $your_path);
 $mkyourfolder = "";

 foreach ($array_folder as $folder) {
   $mkyourfolder = $mkyourfolder . $folder . "/";
   if (!is_dir($mkyourfolder)) {
     mkdir($mkyourfolder, 0777);
   }
  }

hope it will help you




回答2:


Dear friends the following answer is tested and used in my script -

<?php
   $url = "http://localhost/Bashar/abc/def/ghi/dfsdfds/get_dir.php";
   $details = parse_url(dirname($url));
   //$base_url = $details['scheme'] . "//" . $details['host'] . "/";
   $paths = explode("/", $details['path']);
   $full_dir = '';
   $init = ($details['host'] == 'localhost') ? '2' : '1';
   for ($i = $init; $i < count($paths); $i++) {
       $full_dir = $full_dir . $paths[$i] . "/";
       if (!is_dir($full_dir)) {
          mkdir($full_dir, 0777);
       }
   }
?>



回答3:


You can actually create nested folders with the mkdir PHP function

mkdir($path, 0777, true); // the true value here = recursively


来源:https://stackoverflow.com/questions/42505716/how-to-make-directory-within-directory-by-php-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!