PHP 提供了豐富的目錄操作函數族,本文系統整理創建、遍歷、讀取、開關目錄等核心功能,並提供最佳實踐代碼模式。
<?php
$dirName = 'php_demo';
// 0777 為最大權限(受 umask 影響),建議顯式指定
$result = mkdir($dirName, 0777, true); // 第三參數 true 支援遞歸創建
if ($result) {
echo "目錄創建成功:$dirName";
} else {
echo "創建失敗,請檢查權限";
}
?>
關鍵點:PHP 5.0+ 支援遞歸創建(第三參數),舊版本需自行遞歸實現。
<?php
function scanDirectory($path) {
$path = rtrim($path, '/\\');
if (!is_dir($path)) return [];
$files = [];
$handle = opendir($path);
while (false !== ($entry = readdir($handle))) {
// 跳過特殊目錄
if ($entry === '.' || $entry === '..') continue;
$fullPath = $path . DIRECTORY_SEPARATOR . $entry;
if (is_dir($fullPath)) {
// 遞歸掃描子目錄
$files = array_merge($files, scanDirectory($fullPath));
} else {
$files[] = $fullPath;
}
}
closedir($handle);
return $files;
}
// 使用範例
$allFiles = scanDirectory('E:/wwwroot');
print_r($allFiles);
?>
<?php
$dirPath = 'storage/logs';
if (is_dir($dirPath)) {
$handle = opendir($dirPath);
if ($handle) {
echo "目錄打開成功,資源 ID: $handle";
// 後續操作...
closedir($handle);
}
} else {
echo "目錄不存在:$dirPath";
}
?>
<?php
$handle = opendir('data');
while (($file = readdir($handle)) !== false) {
echo "$file
";
}
closedir($handle);
?>
<?php
$handle = opendir('data');
echo "第一次讀取:";
echo readdir($handle); // 讀取第一項
rewinddir($handle); // 重置到開頭
echo "重置後讀取:";
echo readdir($handle); // 再次讀取第一項
closedir($handle);
?>
closedir() 無返回值,無法用於判斷關閉是否成功,但必須調用以釋放資源。
PHP 5.3+ 推薦使用 RecursiveDirectoryIterator:
<?php
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('path/to/dir', FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isFile()) {
echo $fileInfo->getPathname() . "
";
}
}
?>
優勢:物件導向、自動處理遞歸、支援過濾器、記憶體效率更高。
<?php
function getDirSize($dir) {
$size = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$size += $file->getSize();
}
}
return $size;
}
// 格式化輸出
function formatBytes($bytes, $precision = 2) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
return round($bytes / (1024 ** $pow), $precision) . ' ' . $units[$pow];
}
echo formatBytes(getDirSize('storage')); // 例:12.45 MB
?>