34

我编写了这个 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);
           }
        }
     }
   }
?>
4

6 回答 6

65
<?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")

于 2012-11-25T19:11:21.947 回答
34
(time()-filectime($path.$file)) < 86400

如果当前时间和文件更改时间相差在86400 秒以内,那么...

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

我认为这可能是你的问题。将其更改为 > 或 >=,它应该可以正常工作。

于 2010-06-27T02:45:03.327 回答
8
  1. 你想要>
  2. 除非您在 Windows 上运行,否则您需要filemtime()
于 2010-06-27T02:44:43.667 回答
7
<?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);?>
于 2013-07-01T11:14:29.770 回答
0

工作正常

$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);
      }
    }
}
}
于 2016-09-08T04:40:54.310 回答
0

$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;
        } 
     }
}

于 2018-09-03T13:10:28.750 回答