Automatically purging old generated files
If your website generates reports on the fly and makes them available for the user to download by saving them to a temp directory on the server, it would be a good idea to delete old files to prevent all your disk space from being chewed up.
The program listed below will purge files older than a specified number of days for an unlimited number of directories that you can specify. If you schedule it to be executed every day, you can rest assured that your temp directory doesn't get stuffed and a surprise "Out of Disk Space" error doesn't occur.
Example HTML/CFML code:
Code:
<!---
Directory Purge, by John Bartlett
john.bartlett@attws.com
Ver 1.01
--->
<cfsetting enablecfoutputonly="Yes">
<!---
The Directory array contains a list of directories to scan and how many days old the files can be before they are purged.
If you set the history value to -1, all files will be deleted. Note that this is the number of days from the current time.
If you specify a history of 0 (kill files over 24 hours old), a file that was generated two hours ago will not be deleted.
<CFSET Directory[1][2]=2> Files over 2 days old (or 24 hours) will be deleted
<CFSET Directory[1][2]=3> Files over 3 days old (or 72 hours) will be deleted
--->
<CFSET Directory=ArrayNew(2)>
<CFSET Directory[1][1]="C:\WINNT\TEMP">
<CFSET Directory[1][2]=7>
<CFLOOP index="loop" from="1" to="#ArrayLen(Directory)#">
<CFIF Directory[loop][1] CONTAINS "/">
<CFSET PathChar="/"> <!--- Unix Directory --->
<CFELSE>
<CFSET PathChar="\"> <!--- NT Directory --->
</CFIF>
<cfdirectory action="LIST" directory="#directory[loop][1]#" name="dir">
<CFSET kill=0>
<CFSET nokill=0>
<CFSET cantkill=0>
<CFLOOP query="dir">
<CFSET cr=CurrentRow>
<CFIF dir.type[cr] EQ "File">
<CFSET tot=tot + 1>
<CFSET Age=DateDiff("d",dir.DateLastModified[cr],Now())>
<CFIF Age GT Directory[loop][2]>
<CFTRY>
<cffile action="DELETE" file="#Directory[loop][1]##PathChar##dir.Name[cr]#">
<CFOUTPUT>#dir.name[cr]# is #Age# days old, deleting<br>#Chr(10)#</CFOUTPUT>
<CFSET kill=kill+1>
<CFCATCH Type="Any">
<CFOUTPUT>#dir.name[cr]# is #Age# days old, *** UNABLE TO DELETE ***<br>#Chr(10)#</CFOUTPUT>
<CFSET cantkill=cantkill + 1>
<CFSET nokill=nokill + 1>
</CFCATCH>
</CFTRY>
<CFELSE>
<CFSET nokill=nokill + 1>
</CFIF>
</CFIF>
</CFLOOP>
</CFLOOP>
<CFOUTPUT>#tot# files total, #kill# files deleted, #nokill# files skipped, unable to delete #cantkill# files</CFOUTPUT>