php Example Method for Creating Multilevel Directories and Cascading Delete Files

  • 2021-12-21 04:16:27
  • OfStack

This article illustrates how php creates multi-level directories and cascades files. Share it for your reference, as follows:

Create a multilevel directory

mkdir Function can only create level 1 directories. If we want to create multi-level directories, we need to write our own functions.


<?php
$path = "one/two/three/four";
function mkdir_p($path,$mode=0700){
  $arr = explode("/",$path);
  $path = '';
  foreach($arr as $v){
    $path .= $v;
    mkdir($path,$mode);
    $path .= "/";
  }
}
mkdir_p($path);

Cascade to delete files

We know that in PHP rmdir Function can only delete empty folders, unlink Can only be used to delete files.

We can write our own functions to delete non-empty folders in cascade.


<?php
$path = $_SERVER['DOCUMENT_ROOT']."lib";
function rmdir_r($path){
  $handle = opendir($path);
  while($file=readdir($handle)){  // Delete all folders 
    $type = filetype($path."/".$file);
    if($file=='.'||$file=="..")
      continue;
    if($type=="file"){
      // If the type is file, delete the 
      unlink($path."/".$file);
    }
    if($type=="dir"){
      // If the type is folder, cascade delete 
      rmdir_r($path."/".$file);
    }
  }
  closedir($handle);
  rmdir($path);
}
rmdir_r($path);

More readers interested in PHP can check the topics of this site: "php File Operation Summary", "PHP Directory Operation Skills Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: