Currently Browsing: Home » Creating A Random String With PHP

Creating A Random String With PHP

There comes a time when you need to create a random String. It might be for a verification code, a complex password, or something you are developing. You might think that its a boring and manual process. Luckily, this is not true.

Below we present a simple way to create random Strings using PHP. All you need is one function with a few lines of code. Let’s begin…

View a Demo Download the Files

The Function

Let’s call this function rand_string. It will require one parameter, $length, that represents the length of the String to produce:

function rand_string( $length ) {

}

Our first priority is to create a String of our own with all the letters that may be used in the random String:

$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

We will refer to parts of this String using a random generator. Once we generate a random integer index, we add the corresponding character – the character at that index – to a finished String. This can be completed using a loop:

$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
	$str .= $chars[ rand( 0, $size - 1 ) ];
}

Alternatively, Bob (see comment below) suggested that you may use the str_shuffle function, which will randomly move characters around in the String. By using a simple substr snippet, it's possible to cut this String down to the specified length.

$str = substr( str_shuffle( $chars ), 0, $length );

Note: If you require a random String that has a greater length than $chars itself, this alternative method will not work.

After that, we can just return the String.

function rand_string( $length ) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	

	$size = strlen( $chars );
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];
	}

	return $str;
}

Usage

Using this function now becomes a walk in the park. Just pass in the length of a random String you want to generate, and store the returned value in a variable:

$my_string = rand_string( 5 );

Customization

To customize this generator to meet your needs, you may edit the $chars variable to only contain the characters of your choice. The rest of the code need not be changed.

That’s all there is to it. Thanks for reading!

This entry was posted on Saturday, April 25th, 2009 at 21:39:32. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Want to be notified when someone replies? Subscribe to this post's comment RSS feed.
Any field marked with a * is required.