php 如何根据php中的创建日期从目录中删除文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2205738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete files from directory based on creation date in php?
提问by Pawel J. Wal
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).
我有一个存储 html 文件的缓存文件夹。它们在需要时会被覆盖,但很多时候,很少使用的页面也会缓存在那里,最终会占用空间(5 周后,驱动器已满,缓存文件超过 270 万个)。
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?
循环遍历包含数十万个文件的目录并删除早于 1 天的文件的最佳方法是什么?
回答by Pawel J. Wal
I think you could go about this by looping through the directory with readdir and delete based on the timestamp:
我认为您可以通过使用 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);
}
?>
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.
在if((time() - $filelastmodified) > 24*3600)将选择的文件超过24小时(24周小时时间每小时3600秒)以上。如果您想要天数,对于超过一周的文件,它应该读取例如 7*24*3600。
Also, note that filemtimereturns the time of last modification of the file, instead of creation date.
另外,请注意filemtime返回文件的最后修改时间,而不是创建日期。
回答by ketan
It should be
它应该是
if((time()-$filelastmodified) > 24*3600 && is_file($file))
to avoid errors for the .and ..directories.
以避免.和..目录出错。
回答by Sarfraz
The below function lists the file based on their creation date:
以下函数根据文件的创建日期列出文件:
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;
}
Example:
例子:
$_list = listdir_by_date($dir);
Now you can loop through the list to see their dates and delete accordingly:
现在您可以遍历列表以查看它们的日期并相应地删除:
$now = time();
$days = 1;
foreach( $_list as $file => $exp ){
if( $exp < $now-60*60*24*$days ){
unlink( $dir . $file );
}
}
回答by Gordon
Try SplIterators
尝试拆分器
// setup timezone and get timestamp for yesterday
date_default_timezone_set('Europe/Berlin'); // change to yours
$yesterday = strtotime('-1 day', time());
// setup path to cache dir and initialize iterator
$path = realpath('/path/to/files'); // change to yours
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path));
// iterate over files in directory and delete them
foreach($objects as $name => $object){
if ($object->isFile() && ($object->getCTime() < $yesterday)) {
// unlink($object);
echo PHP_EOL, 'deleted ' . $object;
}
}
回答by Lachit
/* Detele Cache Files Here */
$dir = "cache/"; /** define the directory **/
/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {
//foreach (glob($dir.'*.*') as $file){
/*** if file is 24 hours (86400 seconds) old then delete it ***/
if (filemtime($file) < time() - 3600) { // 1 hour
unlink($file);
}
}
I am using this, hope it helps.
我正在使用这个,希望它有所帮助。
回答by Sandra
just to note Gordon's time comparison (see above: https://stackoverflow.com/a/2205833/1875965) is the only correct one when comparing to 'days' rather than '24 hours', as not all days have 24 hours (summertime/wintertime etc).
只是要注意戈登的时间比较(见上文:https: //stackoverflow.com/a/2205833/1875965)是与“天”而不是“24小时”比较时唯一正确的,因为并非所有天都有24小时(夏季/冬季等)。
E.g. use
例如使用
// setup timezone and get timestamp for yesterday
date_default_timezone_set('Europe/Berlin'); // change as appropriate
$yesterday = strtotime('-1 day', time());
when comparing the file date.
比较文件日期时。
This may not be a big issue, but can lead to unexpected behaviour when you're working with weeks/months etc. I found it best to stick to using the above method as it'll make any process involving dates/times consistent and avoid confusion.
这可能不是一个大问题,但是当您处理周/月等时可能会导致意外行为。我发现最好坚持使用上述方法,因为它会使任何涉及日期/时间的过程保持一致并避免困惑。
Also check what the timezone is for the file dates, as sometimes the default for PHP differs from the system timezone.
还要检查文件日期的时区,因为有时 PHP 的默认时区与系统时区不同。
Kind regards, Sandra.
亲切的问候,桑德拉。
回答by trante
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.
通过更改@pawel 的解决方案,我在下面创建了函数。起初我忘记在文件名中添加“路径”,这需要我半个小时才能找到。
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);
}
}

