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

Código php para percorrer um diretório específico e armazenar informações de atributos de todos os arquivos dentro

O projeto requer, é necessário escrever uma função que possa percorrer todos os arquivos em um diretório especificado, além de percorrer também os subdiretórios dentro desse diretório. Exibir as informações de propriedades dos arquivos e armazená-las.

Pense na demanda, não é só um 'ls' -Comando 'al', para obter as propriedades relacionadas, basta adicionar um loop.

Durante o processo do projeto, para facilitar a operação, foi usado o formato JSON para armazenamento, mas também foram encontrados alguns problemas. Registo a seguir os problemas e o código, para referência.

<?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];//经测试这个操作比较耗时,大概0.7s的样子,慎用!
        }
      }
    }
    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];
  }

Isso é tudo o que há no artigo, esperamos que ajude no seu aprendizado e que você apoie o tutorial Grito.

Declaração: O conteúdo deste artigo é de origem na internet, pertence ao respectivo proprietário, foi submetido e carregado voluntariamente pelos usuários da Internet, este site não possui direitos de propriedade, não foi editado manualmente e não assume responsabilidade por eventuais responsabilidades legais. Se você encontrar conteúdo suspeito de violação de direitos autorais, por favor, envie e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas relevantes. Em caso de verificação, o site deletará imediatamente o conteúdo suspeito de violação de direitos autorais.)

Você também pode gostar