関数 opendir

関数 opendir は指定されたディレクトリをオープンし、その記述子(リソース)を返します。この記述子はその後、ディレクトリの内容を読み取る関数と共に使用されます。ディレクトリの使用が終わったら、closedir を使って閉じる必要があります。

構文

phpopendir(string $path, resource $context = null): resource|false

例

opendir の基本的な使用法:

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

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

php"."
".."
"file1.txt"
"subdirectory"

例

ディレクトリオープンエラーの処理:

php<?php
  $dir = opendir('/nonexistent/path');
  if ($dir === false) {
    echo "ディレクトリを開けませんでした";
  } else {
    // ディレクトリの操作
    closedir($dir);
  }
?>

コードの実行結果:

php"ディレクトリを開けませんでした"

例

ストリームコンテキストの使用:

php<?php
  $context = stream_context_create();
  $dir = opendir('ftp://user:password@example.com/', $context);
  if ($dir) {
    // FTPディレクトリの内容を読み取る
    closedir($dir);
  }
?>

この例では、リモートディレクトリの内容を読み取るためにFTPサーバーへの接続を開いています。

関連項目

  • 関数 readdir,
    オープンされたディレクトリの内容を読み取る
  • 関数 closedir,
    ディレクトリ記述子を閉じる
  • 関数 scandir,
    ファイルとディレクトリのリストを配列として返す