PHP – Generate A Random String

The following piece of code could generate a random string with a specified length.

<?php
	/**	Generate random password
	 *	
	 *	Author: Jon Haworth
	 *	Source: http://www.laughing-buddha.net/jon/php/password/
	 */
	function generatePassword ($length = 6) {
		// start with a blank password
		$password = "";

		// define possible characters
		$possible = "0123456789bcdfghjkmnpqrstvwxyz"; 

		// set up a counter
		$i = 0; 

		// add random characters to $password until $length is reached
		while ($i < $length) { 
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

			// we don't want this character if it's already in the password
			if (!strstr($password, $char)) { 
				$password .= $char;
				$i++;
			}
		}
		// done!
		return $password;
	}
	
	// Show the password in browser
	echo generatePassword();
?>      

The generated string would not contains duplicated letter. so if you try to create a string longer then $possible, the while-loop will loop forever.

In case u don’t mind having duplicated letters, just removed the “if (!strstr($password, $char)) { “ condition.

Done =)

Reference: PHP: Generate random password by Jon Haworth

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.