Page 1 of 1

Delete files not modified in last week

Posted: Tue Feb 01, 2005 5:47 pm
by RyanGatewood
I am trying to find a way to delete any folders if a file in it hasnt been modified within the last week.

i have a directory structure like:

test/james/file.txt
test/josh/file.txt
test/jamie/file.txt

i want to find a way to go throught all the directories inside test, and look for file.txt in each directory in test, and if that file hasnt been modified, then it deletes the entire directory.

so suppose

text/james/file.txt has been modified today, it is left alone
test/josh/file.txt was last modified a week and 3 days ago, we dlete the entire "josh" directory.....

any ideas???

i basicly want to setup a cron job to run this script at midnight every night so i dont have stale directories on my server.

Posted: Tue Feb 01, 2005 6:38 pm
by feyd
filemtime()
glob() / opendir()

Posted: Fri Feb 04, 2005 6:39 am
by MrKnight
i did something; take a look

Code: Select all

function deleteStaleFile ($dirName) {
	$d = dir($dirName);
	while($entry = $d->read()) {
		if ($entry != "." && $entry != "..") {
			if (is_dir($dirName."/".$entry)) {
				deleteStaleFile($dirName."/".$entry);
			} else {
				//echo $dirName."/".$entry."\n";
				/* modified zone (by me) starts */
				$file = $dirName."/".$entry;
				if (preg_match('/file.txt/', $entry)){
					$sevendaysago = mktime(date('H'),date('i'),date('s'),date('m'),date('d')-7,date('Y'));
					$filemtime = filemtime($file);
					if ($filemtime < $sevendaysago)&#123;
						$delete = unlink($file);
						if ($delete)
						print "<b>$entry</b> has been deleted, it lastly modified in ".date("d/m/Y",$filemtime);
					&#125;
				&#125;

				/* modified zone (by me) ends */
			&#125;
		&#125;
	&#125;
	clearstatcache();
	$d->close();
&#125;
deleteStaleFile("test/");
i saw the function on php (offline) manual that it doesnt seem on online manual right now, or i couldn't find it, anyways nevermind...
i modified the function for you, you can improve it more.
take it easy!

original function
mikeh at fried-line dot com (28-Jan-2001 01:41)

This lists all files from here (".") on down. [Linux;Apache/1.3.4;PHP 3.0.15]
<?php
function getDirList ($dirName) {
$d = dir($dirName);
while($entry = $d->read()) {
if ($entry != "." && $entry != "..") {
if (is_dir($dirName."/".$entry)) {
getDirList($dirName."/".$entry);
} else {
echo $dirName."/".$entry."
\n";
}
}
}
$d->close();
}
getDirList(".");
?>

Posted: Fri Feb 04, 2005 8:14 am
by feyd
your mktime call could easily be done with a single call to strtotime('-7 days');

Posted: Sat Feb 05, 2005 4:47 am
by MrKnight
yes that sounds good sense, also we can do that

Code: Select all

if (unlink($file)) print ...
instead of

Code: Select all

$delete = unlink($file); 
 if ($delete) print ...
also you can scan not only file.txt, but also all files with extension .txt by
a small changing

Code: Select all

... preg_match('/\.txt$/', $file) ...