In this tutorial I will teach you how to create a random string of letters and digits. This can be used for making random passwords.
First we have to setup the variables.
1: <cfset chars = "0123456789abcdefghiklmnopqrstuvwxyz" / >
2: <cfset strLength = 6 / >
3: <cfset randout = "" / >
The variable chars is a string of letters and numbers that we want to be randomly chosen (We could put capital letters in here also). strLength is the length of the random string that will be created. randout is going to be the name of the string that gets outputted.
Next we make a loop.
4: <cfloop from="1" to="#strLength#" index="i">
5: <cfset rnum = ceiling(rand() * len(chars)) / >
6: <cfif rnum EQ 0 ><cfset rnum = 1 / ></cfif>
7: <cfset randout = randout & mid(chars, rnum, 1) / >
8: </cfloop>
Now lets go through that code.
Line 4 creates a loop that will be repeated as many times as the strLength that we set in line 2 (in this case 6).
Get ready for this one.
Line 5 makes a random number (from 0 to 1) then multiplys that by the length of the variable chars (which in our case is 35) then using the "ceiling()" function rounds that number up.
There is a posibility that rnum can equal 0 which will throw an error. So to prevent that we add in an if statement to see if rnum equals 0. If it does then it will set rnum to 1.
Next in line 7 we give a value to the randout variable. Using the mid() function, it chooses a random location in the "chars" variable and takes a single digit or letter out of it. Then that digit/character gets added to the randout string and the process starts again until we have 6 random digits/characters.
And thats it!!
Editable variables: chars (must be more than 2 characters), strLength (must be over 1)
Hope this tutorial helps!