함수 opendir

함수 opendir는 지정된 디렉토리를 열고, 이후 디렉토리 내용 읽기 함수와 함께 사용되는 해당 디렉토리의 핸들(리소스)을 반환합니다. 디렉토리 작업을 마친 후에는 closedir을 사용하여 닫아야 합니다[citation:1].

구문

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 서버에 연결을 엽니다[citation:2][citation:3].

함께 보기

  • 열린 디렉토리의 내용을 읽는 함수 readdir
  • 디렉토리 핸들을 닫는 함수 closedir
  • 파일 및 디렉토리 목록을 배열로 반환하는 함수 scandir[citation:1]