Page 1 of 1

Delete files from folder with timing

Posted: Thu Nov 10, 2011 2:46 am
by agriz
Hi,

How to delete files from a folder?
I want to delete the files which are 3600 minutes older.

Thanks

Re: Delete files from folder with timing

Posted: Thu Nov 10, 2011 3:12 am
by twinedev
easy way:

Code: Select all

<?php 
    system('tmpwatch -m 60 /path/to/clear');
?>
Note tmpwatch takes HOURS for time 3600/60. Also note, this does it recursively, ie does it to sub directories too. (see http://linux.about.com/library/cmd/blcmdl8_tmpwatch.htm for more information)

If you are needing to do this constantly, I would look at making this a cron that runs once every hour or so.

If you do not have access to run system() (some hosts can shut this off on you for security reasons), then you will need to do something like the following (They are the same, just the first one is broken out more so you can see what is doing easier):

Code: Select all

$strDir = '/path/to/clear/'; // make sure to have trailing /
$intMinues = 3600;

if (is_dir($strDir)) {
    if ($dh = opendir($dir)) {
        while (($strFile = readdir($dh)) !== FALSE) {
            if ($strFile!='.' && $strFile!='..') {
                if (is_file($strDir.$strFile)) {
                    if (filemtime($strDir.$strFile)+$intMinues*60 < time()) {
                        unlink($strDir.$strFile);
                    }
                }
            }
        }
    }
}

Code: Select all

$strDir = '/path/to/clear/'; // make sure to have trailing /
$intMinues = 3600;

if (is_dir($strDir) && ($dh = opendir($dir))) {
    while (($strFile = readdir($dh)) !== FALSE) {
        if ($strFile!='.' && $strFile!='..' && is_file($strDir.$strFile)) {
            if (filemtime($strDir.$strFile)+$intMinues*60 < time()) {
                unlink($strDir.$strFile);
            }
        }
    }
}
-Greg

Re: Delete files from folder with timing

Posted: Thu Nov 10, 2011 3:37 am
by agriz
Awesome, Thanks a lot!!!