如何根据创建日期在PHP中从目录中删除文件? [英] How to delete files from directory based on creation date in php?
问题描述
我有一个存储html文件的缓存文件夹.它们会在需要时被覆盖,但是很多时候,很少使用的页面也会在那里缓存,最终仅占用空间(5周后,驱动器已满了270万个缓存文件).
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).
循环访问包含数十万个文件的目录并删除早于1天的文件的最佳方法是什么?
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?
推荐答案
我认为您可以通过使用readdir遍历目录并根据时间戳删除来解决此问题:
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);
}
?>
if((time() - $filelastmodified) > 24*3600)
将选择早于24小时(24小时乘以每小时3600秒)的文件.如果您希望使用几天,则对于一周以上的文件,它应显示为例如7 * 24 * 3600.
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.
此外,请注意filemtime
返回文件的最后修改时间,而不是创建日期.
Also, note that filemtime
returns the time of last modification of the file, instead of creation date.
这篇关于如何根据创建日期在PHP中从目录中删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!