首頁  >  問答  >  主體

刪除超過一個月的文件 yyyy-mm-dd.pdf

我想根據檔案名稱刪除超過一個月的 pdf 檔案。例如,如果(今天 - 1 個月)是“2022-06-01.pdf”,那麼我想刪除“2022-04-13.pdf”和“2021-01-22.pdf”等文件。我不想根據實際修改或建立日期來確定選擇標準。

範例(臨時/)

#
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 ."'"))}    
}
}

?>

P粉158473780P粉158473780211 天前392

全部回覆(1)我來回復

  • P粉147747637

    P粉1477476372024-02-26 19:51:10

    我會完全在伺服器端完成此操作。

    1. 「1個月前」建立一個DateTime實例
    2. 從該實例建立檔案名稱
    3. 迭代檔案並比較基本名稱(忽略任何目錄前綴)
    4. 如果檔案名稱代表「1 個月前」之前的日期,請將其刪除
    $lastMonth = new DateTimeImmutable('-1 month');
    $cutoff = sprintf('%s.pdf', $lastMonth->format('Y-m-d'));
    
    $glob = glob("temp/2???-??-??.pdf");
    
    foreach($glob as $file) {
        if (basename($file) < $cutoff) {
            unlink($file);
        }
    }
    

    回覆
    0
  • 取消回覆