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

PHP 批量重命名與刪除檔案:目錄遍歷配合 rename/unlink 迴圈

     編輯:程式設計綜合問答

PHP 內建 rename()、unlink()、rmdir() 僅操作單一檔案/目錄,批量處理需結合 目錄掃描函式(scandir、glob、DirectoryIterator)與 迴圈實現。

批量重命名範例

$dir = '/path/to/files';
$files = scandir($dir);
foreach ($files as $file) {
    if ($file === '.' || $file === '..') continue;
    $oldPath = $dir . '/' . $file;
    // 例:在檔名前加前綴 "new_"
    $newName = 'new_' . $file;
    $newPath = $dir . '/' . $newName;
    if (rename($oldPath, $newPath)) {
        echo "Renamed: $file -> $newName\n";
    } else {
        echo "Failed: $file\n";
    }
}

批量刪除範例(含子目錄遞迴)

function deleteAll($path) {
    if (is_file($path) || is_link($path)) {
        return unlink($path);
    }
    if (!is_dir($path)) return false;
    $items = scandir($path);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        if (!deleteAll($path . '/' . $item)) return false;
    }
    return rmdir($path);
}

// 使用
deleteAll('/path/to/target_dir');

進階:使用 SPL DirectoryIterator(物件導向、記憶體友善)

$dir = new RecursiveDirectoryIterator('/path', FilesystemIterator::SKIP_DOTS);
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iter as $fileInfo) {
    if ($fileInfo->isFile()) {
        unlink($fileInfo->getPathname());
    } elseif ($fileInfo->isDir()) {
        rmdir($fileInfo->getPathname());
    }
}

常見陷阱與建議

  • 權限:PHP 執行身分(apache/www-data/php-fpm user)需有目錄寫入/執行權限。
  • 並發:批量操作期間目錄結構可能變更,建議先掃描建立檔案清單陣列,再遍歷陣列操作。
  • 大量檔案效能:scandir 一次載入所有檔名至記憶體,超大目錄(>10萬檔)改用 DirectoryIterator 流式處理。
  • 跨檔案系統:rename() 若源與目標不在同一掛載點會失敗,需改用 copy() + unlink()。
  • 安全:嚴格驗證路徑參數,防止目錄遍歷攻擊(../../etc/passwd)。

參考資源

PHP 目錄遍歷批量操作完整範例

掌握目錄掃描與迴圈組合,即可靈活實現任意批量檔案操作邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved