readdir関数

関数 readdir は、opendir を使用して開かれたディレクトリの内容を読み取ります。呼び出しごとに次のファイル名を返し、ファイルがこれ以上ない場合は false を返します。この関数はディレクトリ内の内部位置ポインタを保持します。

構文

phpreaddir(resource $dir_handle): string|false

例

ディレクトリ内のすべてのファイルを読み取る:

php<?php
  $dir = opendir('/path/to/directory');
  
  while (($file = readdir($dir)) !== false) {
    echo $file . '<br>';
  }
  closedir($dir);
?>

コード実行結果(出力例):

php"file1.txt"
"file2.jpg"
"subdirectory"

例

特別なエントリ '.' と '..' を除外する:

php<?php
  $dir = opendir('.');
  
  while (($file = readdir($dir)) !== false) {
    if ($file != '.' && $file != '..') {
      echo $file . '<br>';
    }
  }
  closedir($dir);
?>

コード実行結果(実際のファイルとサブディレクトリのみを出力):

php'index.php'
'styles.css'
'images'

例

すべてのファイルを配列に収集する:

php<?php
  $files = [];
  if ($handle = opendir('/path/to/dir')) {
    while (false !== ($entry = readdir($handle))) {
      if ($entry != '.' && $entry != '..') {
        $files[] = $entry;
      }
    }
    closedir($handle);
  }
  print_r($files);
?>

コード実行結果:

phpArray
(
  [0] => "document.pdf"
  [1] => "image.png"
  [2] => "data.json"
)

関連項目

  • 関数 opendir,
    ディレクトリハンドルを開きます。
  • 関数 scandir,
    ディレクトリ内のすべてのファイルを配列として返します。