Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

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

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 space (after 5 weeks, the drive was full with over 2.7 million cache files).

Whats the best way to loop thru a directory that contains several hundreds of thousands of files, and remove files that are older than 1 day?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...