Random strings in PHP

Generating a random string value in PHP (e.g a Captcha code):
function djRandomStringPHP() {
	$seed = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
	$rnd_str = substr(str_shuffle($seed), 0, 5);
	
	return $rnd_str;
}


A less PHP-specific way of doing the same thing:
function djRandomString() {
	$seed = array(
	'a','b','c','d','e','f','g','h','i','j','k','m',
	'n','p','q','r','s','t','u','v','w','x','y','z',
	'A','B','C','D','E','F','G','H','J','K','L','M',
	'N','P','Q','R','S','T','U','V','W','X','Y','Z',
	'2','3','4','5','6','7','8','9');

	$rnd_str = '';
	for ($loop_b = 1; $loop_b <= 5; $loop_b++) {
		$rnd_str .= $seed[mt_rand(0, count($seed)-1)];
	}

	return $rnd_str;
}


djRandomStringPHP(): LTFGE
djRandomString(): EuFxH
Refresh page for new results.

Both of the above functions will generate a 5-length value. This will provide one value out of 550731776 possible combinations as an example. I have stripped out the following characters: 1, I, l, o, O and 0 (as they can be confusing to read and type).

This document was last updated July 6th, 2011.
Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0