如何根据php中的创建日期从目录中删除文件?

28 php

我有一个存储html文件的缓存文件夹.它们会在需要时被覆盖,但很多时候,很少使用的页面也被缓存在那里,最终会占用空间(5周之后,驱动器已经满了超过270万个缓存文件).

什么是循环通过包含数十万个文件的目录的最佳方法,并删除超过1天的文件?

Paw*_*Wal 46

我想你可以通过使用readdir循环遍历目录并根据时间戳删除:

<?php
$path = '/path/to/files/';
if ($handle = opendir($path)) {

    while (false !== ($file = readdir($handle))) { 
        $filelastmodified = filemtime($path . $file);
        //24 hours in a day * 3600 seconds per hour
        if((time() - $filelastmodified) > 24*3600)
        {
           unlink($path . $file);
        }

    }

    closedir($handle); 
}
?>
Run Code Online (Sandbox Code Playgroud)

if((time() - $filelastmodified) > 24*3600)将选择的文件超过24小时之前(24小时时间每小时3600秒).如果您想要几天,那么对于超过一周的文件,它应该为7*24*3600读取.

另外,请注意filemtime返回文件的上次修改时间,而不是创建日期.


小智 10

它应该是

if((time()-$filelastmodified) > 24*3600 && is_file($file))
Run Code Online (Sandbox Code Playgroud)

避免...目录的错误.

  • 最好检查是否“$file == ”。|| $file == '..'` 可以节省每次检查 `is_file()` 的时间... (2认同)

Sar*_*raz 5

以下函数根据创建日期列出文件:

private function listdir_by_date( $dir ){
  $h = opendir( $dir );
  $_list = array();
  while( $file = readdir( $h ) ){
    if( $file != '.' and $file != '..' ){
      $ctime = filectime( $dir . $file );
      $_list[ $file ] = $ctime;
    }
  }
  closedir( $h );
  krsort( $_list );
  return $_list;
}
Run Code Online (Sandbox Code Playgroud)

例:

$_list = listdir_by_date($dir);
Run Code Online (Sandbox Code Playgroud)

现在,您可以遍历列表以查看其日期并相应地删除:

$now = time();
$days = 1;
foreach( $_list as $file => $exp ){
  if( $exp < $now-60*60*24*$days ){
    unlink( $dir . $file );
  }
}
Run Code Online (Sandbox Code Playgroud)