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.
Delete files not modified in last week
Moderator: General Moderators
-
RyanGatewood
- Forum Newbie
- Posts: 3
- Joined: Fri Oct 29, 2004 3:10 pm
i did something; take a look
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
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){
$delete = unlink($file);
if ($delete)
print "<b>$entry</b> has been deleted, it lastly modified in ".date("d/m/Y",$filemtime);
}
}
/* modified zone (by me) ends */
}
}
}
clearstatcache();
$d->close();
}
deleteStaleFile("test/");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(".");
?>
yes that sounds good sense, also we can do that
instead of
also you can scan not only file.txt, but also all files with extension .txt by
a small changing
Code: Select all
if (unlink($file)) print ...Code: Select all
$delete = unlink($file);
if ($delete) print ...a small changing
Code: Select all
... preg_match('/\.txt$/', $file) ...