関数 opendir
関数 opendir は指定されたディレクトリをオープンし、その記述子(リソース)を返します。この記述子はその後、ディレクトリの内容を読み取る関数と共に使用されます。ディレクトリの使用が終わったら、closedir を使って閉じる必要があります。
構文
opendir(string $path, resource $context = null): resource|false
例
opendir の基本的な使用法:
<?php
$dir = opendir('/path/to/directory');
if ($dir) {
while (($file = readdir($dir)) !== false) {
echo $file . "\n";
}
closedir($dir);
}
?>
コードの実行結果(出力例):
"."
".."
"file1.txt"
"subdirectory"
例
ディレクトリオープンエラーの処理:
<?php
$dir = opendir('/nonexistent/path');
if ($dir === false) {
echo "ディレクトリを開けませんでした";
} else {
// ディレクトリの操作
closedir($dir);
}
?>
コードの実行結果:
"ディレクトリを開けませんでした"
例
ストリームコンテキストの使用:
<?php
$context = stream_context_create();
$dir = opendir('ftp://user:password@example.com/', $context);
if ($dir) {
// FTPディレクトリの内容を読み取る
closedir($dir);
}
?>
この例では、リモートディレクトリの内容を読み取るためにFTPサーバーへの接続を開いています。