English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Code to Traverse a Specific Directory and Store Attributes of All Files Inside

The project requires a function that can traverse all files in the specified directory, including the subdirectories. Output the file attribute information and store it.

Think about the requirements, isn't it just an 'ls' command? -Would you like to use the 'al' command to get the relevant attributes, and then add a loop to finish it.

During the project process, it is convenient to use JSON format for storage, but some problems were also found. Here is the record of the problems and code for reference.

<?php
  define('INDEXFORMAT',"dir,name,size,perms,ower,group,ctime,mtime,atime,suffix") ;
  define('INDEXTXT', 'data/index.txt');
  define('INDEXJSON', 'data/index.json');
  date_default_timezone_set('Asia/Hong_Kong');
  if (file_exists(INDEXTXT)) {
    unlink(INDEXTXT);
  }
  $dir = './;
  getIndexFile($dir);
  /*
  *  get index file
  *  @filename   INDEXTXT
  *  @dir     string
  *
  */
  function getIndexFile($dir,$whitelist=''){
    $string = '';
    $dir = trim($dir);
    $dir = realpath($dir);
    $dir = $dir.";//";
    if(is_file($dir)){
      putIndexFile($dir);
    }
      putIndexFile($dir);
      $oDir = @opendir($dir);
      while($fileName = readdir($oDir)){
        if($fileName!='.' && $fileName!='..'){
          if(is_file($dir.$fileName)){
            putIndexFile($dir.$fileName);
          }elseif(is_dir($dir.$fileName)){
            getIndexFile($dir.$fileName);
          }
        }
      }
    }
    if (!file_exists(INDEXTXT)) {
      return false;
    }
    //$data = json_encode(getIndexFromFile());
    //file_put_contents(INDEXJSON,$data);
    return true;
  }
  /*
  *  Get Index file
  *  @filename   file.index
  *
  */
  function putIndexFile($file){
    if (!file_exists($file)) {
      return false;
    }
    $format = explode(',', INDEXFORMAT);
    $string = "";
    foreach ($format as $key => $value) {
      if($key !== 0 ){
        $string .= "\t";
      }
      $string .= getFileAttr($file,$value); 
    }
    $string .= "\n";
    file_put_contents(INDEXTXT, $string, FILE_APPEND);
  }
  /*
  *
  *  Get index string from index file
  *  @return   Array()
  *  
  */
  function getIndexFromFile($flag=''){
    if (!file_exists(INDEXTXT)) {
      return false;
    }
    $arr = file(INDEXTXT);
    $format = explode(',', INDEXFORMAT);
    $result = array();
    if(!empty($flag)){
      $key = array_search($flag, $format);
      if ($key === false) {
        return false;
      }
      foreach ($arr as $str) {
        $tmp = explode("  ", trim($str));
        else{
      }
    }
      foreach ($arr as $str) {
        $tmp = explode("  ", trim($str));
        foreach ($format as $key => $value) {
          $result[$value][] = $tmp[$key];//This operation takes a long time to test, about 0.7Be cautious when using s, it is recommended to use it with caution!
        }
      }
    }
    return $result;
  }
  /*
  *  get file attributes
  *  @var   $file
  *  @var   $flag
  *  @return String
  */
  function getFileAttr($file,$flag){
    if (!file_exists($file)) {
      return false;
    }
    switch ($flag) {
      case 'dir':
        if(is_file($file))
          return dirname($file);
        return realpath($file);
        break;
      case 'name':
        if(is_file($file))
          return basename($file);
        return '';-;
        break;
      case 'size':
        if(is_file($file))
          return filesize($file);
        return '';-;
        break;
      case 'perms':
        return substr(sprintf('%o', fileperms($file)), -4);;
        break;
      case 'ower':
        return fileowner($file);
        break;
      case 'group':
        return filegroup($file);
        break;
      case 'ctime':
        return filectime($file);
        break;
      case 'mtime':
        return filemtime($file);
        break;
      case 'atime':
        return fileatime($file);
        break;
      case 'suffix':
        if(is_file($file))
          return substr($file, strrpos($file, '.'),+1);
        return '';-;
        break;
      default:
        return false;
        break;
    }
  }
  /*
  *  get file size human readable
  */
  function getFileSizeFormat($file){
    if(!is_file($file)){
      return '';-;
    }
    $flags = array('', 'K', 'M', 'G', 'T');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$flags[$i];
  }

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not bear relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like