Auto delete all files after x-time

后端 未结 8 1380
春和景丽
春和景丽 2020-12-28 10:04

How do you auto delete all files under a sub directory after x-time (let say after 24 hours) - without using a cronjob command from server or pl. How can you do this just us

相关标签:
8条回答
  • 2020-12-28 10:34
    $path = 'folder/subfolder/';
    
    /* foreach (glob($path.'.txt') as $file) { */
    foreach (glob($path.'*') as $file) {
    
        if(time() - filectime($file) > 86400){
          unlink($file);
        }
    }
    
    0 讨论(0)
  • 2020-12-28 10:35

    After trying to use these examples, I hit a couple of issues:

    1. The comparison operator should be greater than, not less than
    2. filemtime returns the modified time. filectime is the time when a file's inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated, which may lead to unexpected results

    I changed the example to use filemtime and fixed the comparison as follows:

    <?php
      $path = dirname(__FILE__).'/files';
      if ($handle = opendir($path)) {
    
        while (false !== ($file = readdir($handle))) {
            if ((time()-filemtime($path.'/'.$file)) > 86400) {  // 86400 = 60*60*24
              if (preg_match('/\.txt$/i', $file)) {
                unlink($path.'/'.$file);
              }
            }
        }
      }
    ?>
    
    0 讨论(0)
提交回复
热议问题