首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 目錄操作實戰:掃描目錄並識別檔案與資料夾類型

     編輯:PHP 綜合知識

核心函數

  • opendir():開啟目錄控制代碼
  • readdir():讀取下一個項目
  • filetype():取得檔案類型(file/dir/link 等)
  • closedir():關閉目錄控制代碼
  • is_dir():檢查是否為目錄

完整程式碼範例

<?php
$dir = "./"; // 當前目錄

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>檔案名稱</th><th>類型</th></tr>";
        
        while (($file = readdir($dh)) !== false) {
            $fullPath = $dir . $file;
            $type = filetype($fullPath);
            echo "<tr>";
            echo "<td>" . htmlspecialchars($file) . "</td>";
            echo "<td>" . $type . "</td>";
            echo "</tr>";
        }
        
        echo "</table>";
        closedir($dh);
    }
}
?>

執行結果範例

檔案名稱類型
.dir
..dir
cmsdir
index.phpfile
index.php.bakfile
mvcdir
shopdir
shop.rarfile
xamppdir

進階應用:遞迴掃描目錄樹

<?php
function scanDirTree($path, $level = 0) {
    $indent = str_repeat("  ", $level);
    $items = scandir($path);
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $fullPath = $path . DIRECTORY_SEPARATOR . $item;
        $isDir = is_dir($fullPath);
        
        echo $indent . ($isDir ? "📁 " : "📄 ") . $item . "<br>";
        
        if ($isDir) {
            scanDirTree($fullPath, $level + 1);
        }
    }
}

scanDirTree(".");

常用檔案類型常數

回傳值意義
file一般檔案
dir目錄
link符號連結
fifo先進先出佇列
block區塊裝置
char字元裝置
unknown未知類型
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved