在 PHP 開發中,遍歷目錄結構是常見需求。無論是建立檔案管理系統、批次處理檔案,或是掃描特定目錄下的資源,opendir() 函數都是核心工具之一。本文將詳細解析 opendir() 的語法、參數、錯誤處理機制,並提供完整可執行的程式碼範例,幫助開發者快速掌握目錄遍歷技巧。
opendir() 函數用於開啟目錄控制代碼,成功時返回目錄流資源,失敗則回傳 false 並觸發警告。
opendir(string $directory, ?resource $context = null): resource|false
| 參數 | 必要性 | 說明 |
|---|---|---|
directory | 必要 | 要開啟的目錄路徑 |
context | 可選 | 串流上下文資源,可修改串流行為(如 FTP 協定選項) |
若目錄不存在或權限不足,函數會拋出 E_WARNING。可使用 @ 抑制錯誤訊息,或搭配 is_dir() 預先檢查:
// 方式 1:抑制錯誤
$handle = @opendir($path);
// 方式 2:預先驗證(推薦)
if (is_dir($path) && ($handle = opendir($path)) !== false) {
// 處理目錄內容
}
以下程式碼示範如何安全地遍歷目錄並輸出檔案名稱與類型:
<?php
$dir = "./";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
// 過濾特殊目錄 . 和 ..
if ($file !== '.' && $file !== '..') {
$fullPath = $dir . $file;
echo "檔案名稱: $file | 類型: " . filetype($fullPath) . "<br>";
}
}
closedir($dh); // 釋放資源
} else {
echo "無法開啟目錄:權限不足或路徑錯誤";
}
} else {
echo "指定路徑不是有效目錄";
}
?>
若需包含子目錄,可封裝為遞迴函數:
function scanDirectory($path, $depth = 0) {
$indent = str_repeat(' ', $depth);
if ($handle = opendir($path)) {
while (($file = readdir($handle)) !== false) {
if ($file !== '.' && $file !== '..') {
$fullPath = $path . DIRECTORY_SEPARATOR . $file;
echo $indent . $file . (is_dir($fullPath) ? '/' : '') . "<br>";
if (is_dir($fullPath)) {
scanDirectory($fullPath, $depth + 1);
}
}
}
closedir($handle);
}
}
scanDirectory(__DIR__);
is_dir() 預檢,避免不必要的警告closedir() 釋放系統資源DIRECTORY_SEPARATOR 常數確保跨平台相容性DirectoryIterator 或 RecursiveDirectoryIterator (SPL) 獲得更好的物件導向介面. 和 ..?A: 這是 Unix/Linux 檔案系統慣例,分別代表目前目錄與上層目錄,遍歷時需手動過濾。
A: 確保 PHP 腳本編碼為 UTF-8,且檔案系統支援 UTF-8。Windows 環境下可能需用 iconv() 轉換編碼。