PHP скрипт для удаления файлов старше 24 часов, удаляет все файлы

Я написал этот PHP-скрипт для удаления старых файлов старше 24 часов, но он удалил все файлы, включая новые:

<?php
  $path = 'ftmp/';
  if ($handle = opendir($path)) {
     while (false !== ($file = readdir($handle))) {
        if ((time()-filectime($path.$file)) < 86400) {  
           if (preg_match('/.pdf$/i', $file)) {
              unlink($path.$file);
           }
        }
     }
   }
?>

6 ответов


(time()-filectime($path.$file)) < 86400

если текущее время и время файла внутри 86400 секунд, затем...

 if (preg_match('/\.pdf$/i', $file)) {
     unlink($path.$file);
 }

Я думаю, что это может быть ваша проблема. Измените его на > или>=, и он должен работать правильно.


<?php

/** define the directory **/
$dir = "images/temp/";

/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {

/*** if file is 24 hours (86400 seconds) old then delete it ***/
if(time() - filectime($file) > 86400){
    unlink($file);
    }
}

?>

вы также можете указать тип файла, добавив расширение после * (групповой) например

для jpg изображений использовать: glob($dir."*.jpg")

для txt-файлов используйте:glob($dir."*.txt")

для htm-файлов используйте:glob($dir."*.htm")


  1. вы хотите .
  2. Если вы не работаете на Windows, вы хотите filemtime() вместо.

<?php   
$dir = getcwd()."/temp/";//dir absolute path
$interval = strtotime('-24 hours');//files older than 24hours

foreach (glob($dir."*") as $file) 
    //delete if older
    if (filemtime($file) <= $interval ) unlink($file);?>

работает отлично

$path = dirname(__FILE__);
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$timer = 300;
$filetime = filectime($file)+$timer;
$time = time();
$count = $time-$filetime;
    if($count >= 0) {
      if (preg_match('/\.png$/i', $file)) {
        unlink($path.'/'.$file);
      }
    }
}
}

$path = '/cache/';
// 86400 = 1day

if ($handle = opendir($path)) {
     while (false !== ($file = readdir($handle))) {
        if ( (integer)(time()-filemtime($path.$file)) > 86400 && $file !== '.' && $file !== '..') {
                unlink($path.$file);
                echo "\r\n the file deleted successfully: " . $path.$file;
        } 
     }
}