94 lines
2.4 KiB
PHP
94 lines
2.4 KiB
PHP
<?php
|
||
/**
|
||
* 清理旧报告文件脚本
|
||
*
|
||
* 此脚本用于自动清理过期的报告文件,保持报告目录整洁
|
||
* 可以通过群晖的计划任务定期执行
|
||
*/
|
||
|
||
// 设置错误报告
|
||
ini_set('display_errors', 1);
|
||
error_reporting(E_ALL);
|
||
|
||
// 配置信息
|
||
$config = [
|
||
// 保留最近的报告数量
|
||
'keep_recent' => 30,
|
||
|
||
// 报告目录
|
||
'reports_dir' => __DIR__ . '/reports/',
|
||
|
||
// 日志文件
|
||
'log_file' => __DIR__ . '/logs/clean_reports.log',
|
||
];
|
||
|
||
// 记录日志
|
||
function log_message($message) {
|
||
global $config;
|
||
|
||
// 确保日志目录存在
|
||
$log_dir = dirname($config['log_file']);
|
||
if (!is_dir($log_dir)) {
|
||
mkdir($log_dir, 0755, true);
|
||
}
|
||
|
||
$date = date('Y-m-d H:i:s');
|
||
$log_entry = "[$date] $message\n";
|
||
|
||
// 写入日志文件
|
||
file_put_contents($config['log_file'], $log_entry, FILE_APPEND);
|
||
|
||
// 如果是CLI模式,也输出到控制台
|
||
if (php_sapi_name() === 'cli') {
|
||
echo $log_entry;
|
||
}
|
||
}
|
||
|
||
// 主程序
|
||
try {
|
||
log_message('===== 开始执行报告清理脚本 =====');
|
||
|
||
// 检查报告目录是否存在
|
||
if (!is_dir($config['reports_dir'])) {
|
||
throw new Exception("报告目录不存在: {$config['reports_dir']}");
|
||
}
|
||
|
||
// 获取所有报告文件
|
||
$reports = glob($config['reports_dir'] . 'report_*.html');
|
||
|
||
if (empty($reports)) {
|
||
log_message('没有找到需要清理的报告文件');
|
||
exit;
|
||
}
|
||
|
||
log_message('找到 ' . count($reports) . ' 个报告文件');
|
||
|
||
// 按修改时间排序(最新的在前)
|
||
usort($reports, function($a, $b) {
|
||
return filemtime($b) - filemtime($a);
|
||
});
|
||
|
||
// 保留最近的N个报告
|
||
$reports_to_keep = array_slice($reports, 0, $config['keep_recent']);
|
||
$reports_to_delete = array_slice($reports, $config['keep_recent']);
|
||
|
||
log_message('将保留最近的 ' . count($reports_to_keep) . ' 个报告');
|
||
log_message('将删除 ' . count($reports_to_delete) . ' 个旧报告');
|
||
|
||
// 删除旧报告
|
||
foreach ($reports_to_delete as $report) {
|
||
$filename = basename($report);
|
||
if (unlink($report)) {
|
||
log_message("已删除: $filename");
|
||
} else {
|
||
log_message("删除失败: $filename");
|
||
}
|
||
}
|
||
|
||
log_message('===== 报告清理完成 =====');
|
||
|
||
} catch (Exception $e) {
|
||
log_message('错误: ' . $e->getMessage());
|
||
}
|
||
?>
|