Along those lines, the lack of a scope on the safeString function bugged me.
I think this would be fine (note, I scoped safeString variable to "arguments"):
<cffunction name="safeString" access="public" hint="strips unsafe
chars" returntype="string" output="false">
<cfargument name="stringToClean" required="true" type="string">
<cfreturn
rereplacenocase(arguments.stringToClean,'[^a-z|A-Z|0-9|_]','','all')>
</cffunction>
And maybe the old one was safe, so long as the arguments scope is
checked first... but better to be safe, than sorry, especially with a
function like that (potentially used quite a bit in loops and
whatnot).
=]
Var scoping might be better, even, because then it's easier to add
extra logic, like replacing " " and "_" with "-":
<cffunction name="safeString" access="public" hint="strips unsafe
chars" returntype="string" output="false">
<cfargument name="stringToClean" required="true" type="string" />
<cfscript>
var uncleanString = arguments.stringToClean;
var cleanString = "";
// replace "_" and " " with "-"
uncleanString = rereplace(uncleanString,'[_| ]','-','all');
// remove any chars besaides A-z 0-9 or "-"
uncleanString =
rereplacenocase(uncleanString,'[^a-z|A-Z|0-9|-]','','all');
// the "+" means "one or more". "---" becomes "-"
uncleanString = rereplace(uncleanString,'[-]+','-','all');
cleanString = uncleanString;
return cleanString;
</cfscript>
</cffunction>
writeoutput(safeString("this_is pretty (&$^*) - c00l!"))
Produces: this-is-pretty-c00l
I made a little attempt at another best practice, too-- keeping the
"clean" variable separate from the "dirty" one.
Not much use in this example, but in larger things, it might prevent
you from accidentally using an "uncleaned" variable (I learned that
one from Dave Watts, and it sounds sound).
-Denny
--
Rather safe than sorry; that was a little pun-ish, neh?
On Sat, Mar 15, 2008 at 5:40 AM, Dominic Watson
<[EMAIL PROTECTED]> wrote:
> Here's an example I posted in a recent thread that I think demonstrates the
> importance of declaring local variables. It is for a UDF but applies to
> methods in cfcs aswell:
>
> <!--- UDF --->
> <cffunction name="foo">
> <cfset i = 100>
> <cfreturn 'bar'>
> </cffunction>
>
> <!--- Calling template --->
> <cfoutput>
> <cfset i = 1>
> <cfloop condition="i LT 10">
> <cfset bar = foo()>
> #i#<br />
> <cfset i = i + 1>
> </cfloop>
> </cfoutput>
>
> HTH
>
> Dominic
>
> Blog it up: http://fusion.dominicwatson.co.uk
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
Adobe® ColdFusion® 8 software 8 is the most important and dramatic release to
date
Get the Free Trial
http://ad.doubleclick.net/clk;160198600;22374440;w
Archive:
http://www.houseoffusion.com/groups/CF-Talk/message.cfm/messageid:301365
Subscription: http://www.houseoffusion.com/groups/CF-Talk/subscribe.cfm
Unsubscribe: http://www.houseoffusion.com/cf_lists/unsubscribe.cfm?user=89.70.4