How to delete files from directory based on creation date in php?

前端 未结 8 1705
囚心锁ツ
囚心锁ツ 2020-11-29 03:52

I have a cache folder that stores html files. They are overwritten when needed, but a lot of the time, rarely used pages are cached in there also, that just end up using sp

相关标签:
8条回答
  • 2020-11-29 04:45

    By changing @pawel's solution I created function below. At first i forgot to add "path" to file name, which take my half hour to find out.

    public function deleteOldFiles ($hours=24) {
        $path='cache'.DS;
        if ( $handle = opendir( $path ) ) {
            while (false !== ($file = readdir($handle))) {
                $filelastmodified = filemtime($path.$file);
                if((time()-$filelastmodified) > 24*3600 && is_file($path.$file))
                {
                    unlink($path.$file);
                }
            }
            closedir($handle);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 04:51

    I think you could go about this by looping through the directory with readdir and delete based on the timestamp:

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

    The if((time() - $filelastmodified) > 24*3600) will select files older than 24 hours (24 hours times 3600 seconds per hour). If you wanted days, it should read for example 7*24*3600 for files older than a week.

    Also, note that filemtime returns the time of last modification of the file, instead of creation date.

    0 讨论(0)
提交回复
热议问题