readdir

(PHP 3, PHP 4, PHP 5)

readdir -- ディレクトリ・ハンドルからのエントリ読み込み

説明

string readdir ( resource dir_handle )

ディレクトリから次のファイルのファイル名を返します。 ファイル名はファイルシステム上に格納されている順番で返されます。

readdir()の戻り値は以下の例のように チェックされることに注目してください。 We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

例 1. カレントディレクトリにある全ファイルのリストを得る

// Note that !== did not exist until 4.0.0-RC2
<?php
if ($handle = opendir('/path/to/files')) {
    echo
"Directory handle: $handle\n";
    echo
"Files:\n";

    
/* This is the correct way to loop over the directory. */
    
while (false !== ($file = readdir($handle))) {
        echo
"$file\n";
    }

    
/* This is the WRONG way to loop over the directory. */
    
while ($file = readdir($handle)) {
        echo
"$file\n";
    }

    
closedir($handle);
}
?>

readdir() は、エントリ . および .. を返すことに 注意してください。これらを必要としない場合には、次のように取り除いて下さい。

例 2. 現在のディレクトリの . および .. を 除いた全てのファイルの一覧を表示。

<?php
if ($handle = opendir('.')) {
    while (
false !== ($file = readdir($handle))) {
        if (
$file != "." && $file != "..") {
            echo
"$file\n";
        }
    }
    
closedir($handle);
}
?>

See also is_dir(), and glob().