A user sent me some code he was having trouble with, and in the code I saw a rather verbose and complex block of CFML being used to generate random strings for use with CAPTCHA verifications. So, while replying to his e-mail, I also sent him the RandString() function I use myself. And, as it may be of use others, here it is:
<!--- Generate random strings of specified length --->
<cffunction name="RandString" output="no" returntype="string">
<cfargument name="length" type="numeric" required="yes">
<!--- Local vars --->
<cfset var result="">
<cfset var i=0>
<!--- Create string --->
<cfloop index="i" from="1" to="#ARGUMENTS.length#">
<!--- Random character in range A-Z --->
<cfset result=result&Chr(RandRange(65, 90))>
</cfloop>
<!--- Return it --->
<cfreturn result>
</cffunction>
--- Ben
http://www.cflib.org/udf.cfm/randstr
It is more complex though. Sometimes simpler is better.
here's a sampling:
<cfset var captchaChars = "2,3,4,5,6,7,8,9,a,b,d,e,f,g,h,j,n,q,r,t,y,A,B,C,D,E,F,G,H,K,L,M,N,P,Q,R,T,U,V,W,X,Y,Z" />
<cfset var cLength = 2 />
<cfset var cString="" />
<cfset var cStringHashed = "" />
<cfset var i = "" />
<!--- Create a loop that builds the string from the random characters. --->
<cfloop from="1" to="#cLength#" index="i">
<cfset cString = cString & listGetAt(captchaChars, RandRange(1, listLen(captchaChars))) />
</cfloop>
<cfset cStringHashed = Hash(ucase(cString)) />
<cffunction name="RandString" output="no" returntype="string">
<cfargument name="length" type="numeric" required="no">
<!--- Local vars --->
<cfset var result="">
<cfset var i=0>
<!--- set a default length --->
<cfparam name="arguments.length" default="#RandRange(5,9)#">
<!--- Create string --->
<cfloop index="i" from="1" to="#ARGUMENTS.length#">
<!--- Random character in range A-Z --->
<cfset result=result&Chr(RandRange(65, 90))>
</cfloop>
<!--- Return it --->
<cfreturn result>
</cffunction>
I like Ben's two character simple captcha, he understands.