简体   繁体   中英

php function to delete all files & folders older than 1 day

i am using this function and it works fine but only problem is it deletes root folder if folder is empty.

if all items are already deleted with previous cron and then again it is called then it will delete forder word. Any help will be great

rrmdir('/path/word');
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) @unlink($dir."/".$object);

            }
        }
        reset($objects);
       rmdir($dir);
    }
}

The difficulty is that it depends on the intention of the caller. Should they pass in a directory and if so - should it remove this directory. As the routine is called rrmdir I would sort of expect it to remove the directory I was passing in.

function rrmdir($dir)
{
    echo $dir.PHP_EOL;
    if (is_dir($dir))
    {
        $objects = scandir($dir);
        foreach ($objects as $object)
        {
            if ($object != "." && $object != "..")
            {
                echo $object.'='.filetype($dir."/".$object).PHP_EOL;
                if (filetype($dir."/".$object) == "dir") {
                    rrmdir($dir."/".$object);
                    rmdir($dir);
                }
                if (filemtime($dir."/".$object) <= time()-60*60*24) unlink($dir."/".$object);

            }
        }
        reset($objects);
        //rmdir($dir);
    }
}

I've moved the rmdir into the test for sub-directories. It was previously removing all directories (including the one passed in).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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