opendir() / readdir() / closedir():目錄句柄操作三部曲。scandir():一次性返回目錄下所有文件名數組(含 . ..)。glob():模式匹配獲取文件列表,如 glob('*.php')。copy() / rename() / unlink():拷貝、移動/重命名、刪除。mkdir() / rmdir():創建/刪除目錄(注意遞歸參數)。fileperms() / chmod() / chown():權限讀取與修改。<?php
function listDirectory(string $path): array {
// 1. 路徑標準化與安全檢查(防止目錄遍歷攻擊)
$realPath = realpath($path);
$basePath = realpath(__DIR__ . '/public_files'); // 限制根目錄
if (!$realPath || strpos($realPath, $basePath) !== 0) {
throw new InvalidArgumentException('非法路徑');
}
$files = [];
$dir = opendir($realPath);
while (($entry = readdir($dir)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$fullPath = $realPath . DIRECTORY_SEPARATOR . $entry;
$files[] = [
'name' => $entry,
'path' => $fullPath,
'is_dir' => is_dir($fullPath),
'size' => is_file($fullPath) ? filesize($fullPath) : null,
'mtime' => filemtime($fullPath),
'perm' => substr(sprintf('%o', fileperms($fullPath)), -4),
];
}
closedir($dir);
return $files;
}
// 使用
try {
$list = listDirectory($_GET['dir'] ?? './public_files');
header('Content-Type: application/json');
echo json_encode($list, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} catch (Exception $e) {
http_response_code(400);
echo $e->getMessage();
}
<?php
function backupFile(string $source, string $destDir): bool {
if (!is_file($source) || !is_readable($source)) {
error_log("源文件不可讀:$source");
return false;
}
if (!is_dir($destDir)) {
mkdir($destDir, 0755, true);
}
$dest = $destDir . DIRECTORY_SEPARATOR . basename($source) . '_' . date('YmdHis');
if (!@copy($source, $dest)) {
error_log("拷貝失敗:$source -> $dest");
return false;
}
// 可選:驗證文件完整性
if (filesize($source) !== filesize($dest)) {
unlink($dest);
error_log("文件大小不一致,備份已回滾");
return false;
}
return true;
}
www-data)必須擁有目標目錄的 rwx 權限。chmod 755 而非 777),並配置 Nginx/Apache 禁用腳本執行。open_basedir 限制,需在 php.ini 配置允許路徑。$iterator = new FilesystemIterator('/var/www/uploads', FilesystemIterator::SKIP_DOTS);
foreach ($iterator as $fileinfo) {
echo $fileinfo->getFilename() . ' - ' . $fileinfo->getSize() . ' bytes
';
}
物件導向風格更優雅,自動實現 Iterator 介面,適合大型項目。