Heim  >  Fragen und Antworten  >  Hauptteil

Löschen Sie Dateien, die älter als einen Monat sind. JJJJ-MM-TT.pdf

Ich möchte PDF-Dateien, die älter als einen Monat sind, anhand ihres Dateinamens löschen. Wenn (heute – 1 Monat) beispielsweise „2022-06-01.pdf“ ist, dann möchte ich Dateien wie „2022-04-13.pdf“ und „2021-01-22.pdf“ löschen. Ich möchte meine Auswahlkriterien nicht auf tatsächlichen Änderungs- oder Erstellungsdaten basieren.

Beispiel (vorübergehend/)

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 Tage vor393

Antworte allen(1)Ich werde antworten

  • 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);
        }
    }
    

    Antwort
    0
  • StornierenAntwort