Random String Generator for CFML
Working on a CFML-based project using components and figured I could document this for my own personal user later. If it helps someone else along the way, even better.
<cffunction name="randomString" returntype="string" hint="generates a random string at a given length with specific characters">
<cfargument name="length" type="integer" required="false" default="16" hint="desired length of the random string">
<cfargument name="charset" type="string" required="false" default="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*&^%$@!-_" hint="character set to generate string from">
<cfset randomString = "">
<cfloop from="0" to="#arguments.length#" index="i">
<cfset randomString &= mid(charset, randRange(1, len(charset), "SHA1PRNG"), 1)>
</cfloop>
<cfreturn randomString>
</cffunction>
Once the method is made, you just invoke the method with the cfinvoke tag. Since I put my component in my /utils/strings.cfc
directory, I could use the following:
<cfinvoke component="util.strings" method="randomString" returnvariable="local.randString"
length="24"
>
I did not specify the charset, because my default will work for my purposes, but you can customize the characters that the random string generator uses by passing them on the invoke tag as the charset variable, like so:
<cfinvoke component="util.strings" method="randomString" returnvariable="local.randString"
length="24"
charaset="abcdefghijklmnopqrstuvwxyz"
>
which would produce a random string using only lower-case letters.
Hope this helps!