dir 클레스를 이용해 해당 디렉토리의 entry 를 가져오기 위해서는 폴더를 먼저 "오픈"하고, "읽기", "닫기" 순으로 작성하면 됩니다.

<?php
 $path = "./mail"; // 오픈하고자 하는 폴더
 $entrys = array(); // 폴더내 Entry를 저장하기 위한 배열
 $dirs = dir($path); // 오픈하기
 while(false !== ($entry = $dirs->read())){ // 읽기
    $entrys[] = $entry;
 }
 $dirs->close(); // 닫기

 var_export($entrys);

 /*
 결과:
 array (
  0 => '.',
  1 => '..',
  2 => 'Mail',
  3 => 'Mail.php',
  4 => 'package.xml',
  5 => 'PEAR.php',
  6 => 'tests',
 )
 */
 ?>

"."와 ".."는 기본적으로 entry 로 가져오게 됩니다. 이를 제외시켜줄 필요가 있으며 폴더와 파일을 구분지어 정리해 줄 필요가 있겠지요. 그래서 다음과 같이 처리해 주었습니다.

<?php
 $path = "./mail"; // 오픈하고자 하는 폴더
 $entrys = array(); // 폴더내의 정보를 저장하기 위한 배열
 $dirs = dir($path); // 오픈하기
 while(false !== ($entry = $dirs->read())){ // 읽기
    if(($entry != '.') && ($entry != '..')) {
        if(is_dir($path.'/'.$entry)) { // 폴더이면
             $entrys['dir'][] = $entry;
        }
        else { // 파일이면
             $entrys['file'][] = $entry;
       }
    }
 }
 $dirs->close(); // 닫기

 $dircnt = count($entrys['dir']); // 폴더 수
 $filecnt = count($entrys['file']); // 파일 수

 echo "폴더 수: ${dircnt} 파일 수:${filecnt}<br/>\n";
 var_export($entrys);

 /*
 결과:
 폴더 수: 2 파일 수:3<br/>
 array (
  'dir' => 
  array (
    0 => 'Mail',
    1 => 'tests',
  ),
  'file' => 
  array (
    0 => 'Mail.php',
    1 => 'package.xml',
    2 => 'PEAR.php',
  ),
 )
 */
 ?>

0 댓글