如何按文件名日期删除超1个月的yyyy-mm-dd.pdf格式旧文件
过期PDF清理需求
- 清理规则:完全不参考文件的创建时间、修改时间属性,仅以PDF文件名中携带的日期信息作为唯一判定依据,删除存放时间超过1个月的文件
- 判定标准:取当前日期往前推1个自然月作为阈值日期,所有文件名对应日期早于该阈值的PDF文件均需删除。例如阈值为
2022-06-01时,2022-04-13.pdf、2021-01-22.pdf都属于待删除范围 - 待处理文件路径:
temp/目录,目录内文件样例如下:
2019-02-01.pdf 2020-07-01.pdf 2021-03-10.pdf 2021-08-04.pdf 2022-03-30.pdf 2019-02-27.pdf 2020-07-08.pdf 2021-03-17.pdf 2021-08-11.pdf 2022-04-06.pdf
原有问题代码
HTML调用代码
oldFiles(); purgeOLD();
JS逻辑代码
function oldFiles() { // this is ok yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 30); actualYear = yesterday.getFullYear(); actualMonth = yesterday.getMonth() + 1; actualDay = yesterday.getDate(); if (actualMonth < "10") {actualMonth = "0" + actualMonth;} if (actualDay < "10") {actualDay = "0" + actualDay;} backtrack = actualYear +'-' +actualMonth +'-' +actualDay; } function purgeOLD () { // is this where the problem is ? var new_data = backtrack; var data; $.ajax({url: 'test.php', type: 'post', async: false, data: {user: new_data}}); }
PHP处理代码(test.php)
<?php // or is this ? $result = $_GET['user']; $rdm = $result .'.pdf'; $glob = glob("temp/2???-??-??.pdf"); foreach($glob as $file) { if ($file < $rdm) { {unlink('/home/example/public_html/temp/' .$file ."'"))} } } ?>
代码问题排查
你的代码JS和PHP部分都有问题,不是单一模块的错误:
JS端问题
- 阈值计算逻辑不符合需求:当前逻辑是减30天,不是往前推1个自然月,遇到大小月、跨2月的场景计算结果完全不对
- 所有变量都未做声明,直接挂载到全局作用域,容易出现变量被覆盖的异常
- 用同步AJAX请求会阻塞主线程,导致页面卡顿
- AJAX请求没有加失败回调,出问题无法排查
PHP端问题
- 核心参数获取错误:前端用POST方式传参,代码里用
$_GET取值,根本拿不到前端传的阈值日期,后续逻辑全是空跑 - 字符串比较的基准不一致:
glob()返回的路径带temp/前缀(比如temp/2022-04-06.pdf),你拼接的对比值$rdm是纯文件名不带路径,字符串比较结果完全错误 - 删除路径拼接错误:多拼了一个多余的单引号,而且glob返回的路径已经带
temp/前缀,你又重复拼接了一次temp目录,路径不存在会导致删除失败 - 没有做参数合法性校验,传入非法日期格式时会出现误删
修正后可运行代码
JS部分
function getThresholdDate() { const now = new Date(); // 直接调用Date构造方法往前推1个自然月,自动处理大小月、闰月问题 const threshold = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate()); const year = threshold.getFullYear(); let month = threshold.getMonth() + 1; let day = threshold.getDate(); // 补前导零 month = month < 10 ? `0${month}` : month; day = day < 10 ? `0${day}` : day; return `${year}-${month}-${day}`; } function purgeOldFiles() { const threshold = getThresholdDate(); $.ajax({ url: 'test.php', type: 'POST', async: true, data: { threshold: threshold }, success: (res) => console.log('清理结果', res), error: (err) => console.error('清理请求失败', err) }); } // 调用执行 purgeOldFiles();
PHP部分(test.php)
<?php // 从POST中取阈值参数,做格式校验 $threshold = $_POST['threshold'] ?? ''; if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $threshold)) { exit(json_encode([ 'code' => 400, 'msg' => '阈值参数格式非法' ])); } $thresholdFileName = $threshold . '.pdf'; // 遍历目录下所有符合命名规则的PDF文件 $files = glob("temp/2???-??-??.pdf"); $deletedCount = 0; foreach ($files as $filePath) { // 提取纯文件名,去掉路径前缀用于日期比较 $fileName = basename($filePath); // YYYY-MM-DD格式的日期字符串字典序和实际日期先后顺序完全一致,可直接比较 if ($fileName < $thresholdFileName) { // 拼接正确的绝对路径,去掉多余字符 $fullPath = '/home/example/public_html/' . $filePath; if (file_exists($fullPath) && is_file($fullPath)) { unlink($fullPath); $deletedCount++; } } } exit(json_encode([ 'code' => 200, 'msg' => '清理完成', 'deleted_count' => $deletedCount ])); ?>
内容的提问来源于stack exchange,提问作者verlager
相关产品推荐
相关产品推荐

