Examples of Directory Operations opendir of readdir of and scandir of Usage in php

  • 2021-12-12 03:57:19
  • OfStack

This article illustrates the usage of directory operations opendir (), readdir () and scandir () in php. Share it for your reference, as follows:

opendir(path,context) If successful, the function returns 1 directory stream, otherwise it returns false and 1 error. You can hide the output of error by preceding the function name with "@".

readdir() Function returns the value of the opendir() The entry in the open directory handle. If successful, the function returns 1 file name, otherwise it returns false.

scandir() The function returns an array containing files and directories in the specified path.
If it succeeds, it returns 1 array, and if it fails, it returns false. If directory is not a directory, the Boolean value false is returned

Pay the code of reading directory found in 2 paragraphs, and the pro-test is valid

Display file names in the directory


//  Open the directory and read its contents 
if (is_dir($dir)){
 if ($dh = opendir($dir)){
  while (($file = readdir($dh)) !== false){
   echo "filename:" . $file . "<br>";
  }
  closedir($dh);
 }
}

Copy files from one directory to another


copy_dir($from_dir,$to_dir);
function copy_dir($from_dir,$to_dir){
  if(!is_dir($from_dir)){
    return false;
  }
  echo "\r\n from:",$from_dir,'---to',$to_dir;
  $from_files = scandir($from_dir);
  // If the destination directory does not exist, try creating a 
  if(!file_exists($to_dir)){
    @mkdir($to_dir);
  }
  if(!empty($from_files)){
    foreach ($from_files as $file){
      if($file == '.' || $file == '..' ){
        continue;
      }
      if(is_dir($from_dir.'/'.$file)){// If it is a directory, call itself 
        copy_dir($from_dir.'/'.$file,$to_dir.'/'.$file);
      }else{// Direct copy To the destination folder 
        copy($from_dir.'/'.$file,$to_dir.'/'.$file);
      }
    }
  }
}

For more readers interested in PHP related contents, please check the topics of this site: "Summary of PHP Directory Operation Skills", "Summary of php File Operation", "Summary of PHP Common Traversal Algorithms and Skills", "Tutorial on PHP Data Structure and Algorithms", "Summary of php Programming Algorithms", "Complete Collection of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage" and "Summary of php Common Database Operation Skills"

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


Related articles: