Delete files from folder with timing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
agriz
Forum Contributor
Posts: 106
Joined: Sun Nov 23, 2008 9:29 pm

Delete files from folder with timing

Post by agriz »

Hi,

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

Thanks
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Delete files from folder with timing

Post 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
agriz
Forum Contributor
Posts: 106
Joined: Sun Nov 23, 2008 9:29 pm

Re: Delete files from folder with timing

Post by agriz »

Awesome, Thanks a lot!!!
Post Reply