上傳目錄常被植入木馬、腳本、異常檔案。本文提供一個遞歸掃描函式,僅保留白名單尺寸的 JPG 圖片,並雙重驗證:副檔名 + `getimagesize()` 真實類型,徹底清理風險檔案。
<?php
/**
* 遞歸刪除目錄下不符合規則的檔案
* @param string $dir 絕對路徑
* @param array $allowNames 允許的檔名陣列(如縮圖命名規則)
*/
function cleanUploadDir(string $dir, array $allowNames = []): void
{
if (!is_dir($dir)) return;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
cleanUploadDir($path, $allowNames);
// 可選:刪除空目錄
if (count(scandir($path)) === 2) @rmdir($path);
} else {
// 檔案過濾邏輯
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$base = basename($file);
// 1. 副檔名必須為 jpg
if ($ext !== 'jpg') {
@unlink($path);
continue;
}
// 2. 檔名必須在白名單(如 180x180.jpg, 30x30.jpg...)
if (!in_array($base, $allowNames, true)) {
@unlink($path);
continue;
}
// 3. 真實圖片類型驗證(防偽裝副檔名)
$info = @getimagesize($path);
if (!$info || $info[2] !== IMAGETYPE_JPEG) {
@unlink($path);
}
}
}
closedir($dh);
}
// 使用範例
$allowed = ['180x180.jpg', '30x30.jpg', '45x45.jpg', '90x90.jpg'];
cleanUploadDir('/var/www/html/uploads/avatar', $allowed);
?>
<?php
function cleanUploadDirSpl(string $dir, array $allowNames): void
{
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST // 先處理檔案再處理目錄
);
foreach ($iterator as $file) {
if (!$file->isFile()) continue;
$base = $file->getBasename();
$ext = strtolower($file->getExtension());
if ($ext !== 'jpg' || !in_array($base, $allowNames, true)) {
@unlink($file->getPathname());
continue;
}
$info = @getimagesize($file->getPathname());
if (!$info || $info[2] !== IMAGETYPE_JPEG) {
@unlink($file->getPathname());
}
}
}
?>
「上傳目錄不可執行、檔案名不可控、類型雙重驗證」是防 WebShell 鐵三角,清理腳本只是最後防線。