简体   繁体   English

删除所有文件,包括3个月以上的子目录中的文件PHP

[英]Delete all files, including those within a sub-directory older than 3 months PHP

I have a 'cache' folder on my webserver where .html files are stored, the file structure is as follows: 我的网络服务器上有一个“缓存”文件夹,用于存储.html文件,文件结构如下:

cache > user@gmail.com > several .html files.

I need a PHP script that will browse all the subdirectors within the user folders and delete files older than 3 months. 我需要一个PHP脚本,该脚本将浏览用户文件夹中的所有子目录并删除3个月以上的文件。

I have this script so far: 到目前为止,我有这个脚本:

$DIR = '/cache/';
if ($handle = opendir($DIR)) {

    while (false !== ($file = readdir($handle))) {
        if ( filemtime($DIR.$file) <= time()-60*60*24*120 ) { //120 days?
           unlink($DIR.$file);
        }
    }

    closedir($handle);
}

But it does not handle sub-directories. 但是它不处理子目录。 It is also giving me errors because it is trying to unlink directorys.. 这也给我错误,因为它正试图取消目录的链接。

Update: trying to add a count feature: 更新:尝试添加计数功能:

<?php

rrmdir(/www/deletecontentsofthisfolder/);
echo $count . ' files deleted!';

function rrmdir($dir,$count=0) 
{
    if (is_dir($dir)) 
    {
        $objects = scandir($dir);
        foreach ($objects as $object) 
        {
            if ($object != "." && $object != "..") 
            {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object,$count);
                if (filemtime($dir."/".$object) <= time()-60*60*24*120) @unlink($dir."/".$object); count++
            }
        }
        reset($objects);
        //rmdir($dir);
    }
return $count;
}
function rrmdir($dir) 
{
    if (is_dir($dir)) 
    {
        $objects = scandir($dir);
        foreach ($objects as $object) 
        {
            if ($object != "." && $object != "..") 
            {
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object);
                if (filemtime($dir."/".$object) <= time()-60*60*24*120) @unlink($dir."/".$object);
            }
        }
        reset($objects);
        //rmdir($dir);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM