需要遍歷指定目錄及所有子目錄,將所有檔案(不含資料夾)重新命名為隨機數字,保留副檔名。
| 函數 | 用途 |
|---|---|
is_dir() | 判斷路徑是否為目錄 |
opendir() / readdir() | 開啟目錄並逐一讀取項目 |
pathinfo() | 解析路徑取得 dirname、basename、extension |
rename() | 重命名檔案/目錄 |
rand() | 產生隨機數 |
<?php
/**
* 遞迴遍歷目錄並重命名所有檔案
* @param string $dirname 目標目錄路徑
*/
function fRename($dirname) {
// 1. 驗證目錄合法性
if (!is_dir($dirname)) {
echo "{$dirname} 不是一個有效的目錄!";
exit();
}
$handle = opendir($dirname);
// 2. 逐一讀取目錄項目
while (($fn = readdir($handle)) !== false) {
// 3. 跳過 . 和 ..
if ($fn !== '.' && $fn !== '..') {
$curDir = $dirname . '/' . $fn;
// 4. 若是目錄 → 遞迴處理
if (is_dir($curDir)) {
fRename($curDir);
}
// 5. 若是檔案 → 隨機重命名
else {
$path = pathinfo($curDir);
// 隨機數 0-100 + 原副檔名
$newname = $path['dirname'] . '/' . rand(0, 100) . '.' . $path['extension'];
rename($curDir, $newname);
echo $curDir . ' --- ' . $newname . "<br/>";
}
}
}
closedir($handle);
}
// 執行:傳入目標目錄名稱
fRename('pl');
?>
!== falsereaddir() 可能回傳 0、"" 等 falsy 值,必須用 全等(=== / !==) 判斷,否則檔名為 "0" 時會誤判為結束。
$path = pathinfo('/path/to/file.txt');
/*
Array(
[dirname] => /path/to
[basename] => file.txt
[extension] => txt
[filename] => file // PHP 5.2+
)
*/
is_dir() 防呆uniqid()、microtime(true)、UUIDRecursiveDirectoryIterator (SPL) 更優雅rename() 失敗時記錄日誌、拋出例外function renameFilesRecursive($dir) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$newName = $file->getPath() . '/' . uniqid() . '.' . $file->getExtension();
rename($file->getPathname(), $newName);
echo "{$file->getPathname()} → {$newName}<br>";
}
}
}
⚠️ 實際部署時務必加入:路徑白名單驗證、權限檢查、操作日誌、乾跑模式、備份機制。切勿直接對使用者輸入路徑執行刪改操作!