PHP – Generate/Create strong passwords, uuid, random string

Very often the need to create passwords or some other ‘unique’ string be it a captcha or for use as unique identifier (UUID).

Here are a few functions I’ve used and refined over the years, 2 types, for password/random string generation and UUID generation.

Generating random strings is pretty simple as it’ll be a password.

However for a UUID there is always the slim chance it’s not unique.

To fully ensure a UUID is actually unique combine any of the functions depending on what yuou prefere with something like:

do{
$newUUID=...//however you generate it...
$result=mysql_query("Select * from $table where youridfield=$newUUID;");
}while(mysql_num_rows($result)>0);

to check if it really does’nt exist first!

Below are some of the outputs that my function(s) generate:

Perfect for: PASSWORD GENERATION
Options: variable length
generateRandStr(8)
result: 4sRBfahW

function generateRandStr_md5 ($length) {
	// Perfect for: PASSWORD GENERATION
	// Generate a random string based on an md5 hash
	$randStr = strtoupper(md5(rand(0, 1000000))); // Create md5 hash
	$rand_start = rand(5,strlen($randStr)); // Get random start point
	if($rand_start+$length > strlen($randStr)) {
		$rand_start -= $length; // make sure it will always be $length long
	} if($rand_start == strlen($randStr)) {
		$rand_start = 1; // otherwise start at beginning!
	}
	// Extract the 'random string' of the required length
	$randStr = strtoupper(substr(md5($randStr), $rand_start, $length));
	return $randStr; // Return the string
}
 
function generateRand_uuid ( $prefix = 'W' ) {
	// Perfect for: UNIQUE ID GENERATION
	// Create a UUID made of: PREFIX:TIMESTAMP:UUID
	$my_random_id = $prefix;
	$my_random_id .= chr ( rand ( 65, 90 ) );
	$my_random_id .= time ();
	$my_random_id .= uniqid ( $prefix );
	return $my_random_id;
}
 
function generateRand_uuid_l ( $prefix = 'W', $length=0 ) {
	// Perfect for: UNIQUE ID GENERATION
	// Create a UUID made of: PREFIX:TIMESTAMP:UUID(PART - LENGTH - or FULL)
	$my_random_id = $prefix;
	$my_random_id .= chr ( rand ( 65, 90 ) );
	$my_random_id .= time ();
	$my_uniqid = uniqid ( $prefix );
	if($length > 0) {
		$my_random_id .= substr($my_uniqid, $length);
	} else {
		$my_random_id .= $my_uniqid;
	}
	return $my_random_id;
}
 
function generateRand_md5uid(){
	// Perfect for: UNIQUE ID GENERATION
	// Create a really STRONG UUID
	// Very high odds of creating a unique string 1:1000000+
	$better_token = md5(uniqid(rand(), true));
	$unique_code = substr($better_token, 64);
	$uniqueid = $unique_code;
	return $better_token;
}
 
?>

Leave a Reply