PHP脚本:删除24小时前的文件,删除所有文件

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

你在使用什么操作系统?Win32还是Unix/Linux? - Aaron Butacov
10
应该不是应该> 86400吗? - neal aise
它在Linux系统上。我看到了我的错误。但是为什么它也删除了旧文件? - ChuckO
因为某些东西正在改变文件的元数据。 - Ignacio Vazquez-Abrams
注意你的尾随斜杠。如果 $path 没有尾随斜杠,这段代码将会失败。 - Tyler V.
7个回答

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


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

如果当前时间和文件修改时间相差不超过86400秒,那么...

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

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


8
<?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);?>

8
  1. 你需要使用>
  2. 除非你在Windows上运行,否则你需要使用filemtime()

2

我测试了两种方法来比较速度。选项A的速度大约快了50%。我在一个包含大约6000个文件的文件夹上运行了此操作。

选项A

$path='cache/';
$cache_max_age=86400; # 24h
if($handle=opendir($path)){
    while($file=readdir($handle)){
        if(substr($file,-6)=='.cache'){
            $filectime=filectime($path.$file);
            if($filectime and $filectime+$cache_max_age<time()){
                unlink($path.'/'.$file);
            }
        }
    }
}

Option B(选项B)
$path='cache/';
$cache_max_age= 86400; # 24h
foreach(glob($path."*.cache") as $file){
    $filectime=filectime($file);
    if($filectime and $filectime+$cache_max_age<time()){
        unlink($file);
    }
}

它还检查文件创建时间是否返回。在某些系统上,返回创建时间会出现问题。因此,我希望确保如果系统没有返回时间戳,则不会删除所有文件。


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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接