Safe file names in ColdFusion
We support over 26 languages in TeamworkPM. Today our backup script failed for one customer because the generated file name had bizarre characters in it. To fix this I amended our safeFileName() function to just use alpha-numeric characters. But if all characters are ripped out and we are left with just the extension (eg. ".zip"), then we fall back to a time-stamp. Here's the code:
<cffunction name="SafeFileName" returntype="string" output="No">
<cfargument name="fileName" required="Yes" type="string">
<cfset var result = ARGUMENTS.fileName>
<cfset result = trim( reReplace( result , "[\ \,]", "_", "ALL" ) )>
<cfset result = reReplace( result , "[^a-zA-Z0-9\.\_]", "", "ALL" ) >
<cfif Len( result ) IS 4 AND Left( result, 1 ) IS ".">
<cfset result = dateFormat(now(),"ddmmyyyy") & timeFormat(now(),"hhmmss") & result>
</cfif>
<cfreturn result>
</cffunction>