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');
$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());
}
}
scandir 一次載入所有檔名至記憶體,超大目錄(>10萬檔)改用 DirectoryIterator 流式處理。rename() 若源與目標不在同一掛載點會失敗,需改用 copy() + unlink()。../../etc/passwd)。掌握目錄掃描與迴圈組合,即可靈活實現任意批量檔案操作邏輯。