jump to navigation

Generate Random Characters With PHP January 6, 2012

Posted by Tournas Dimitrios in PHP.
trackback

There are times when you need to get a string of random characters of the specified length . It could be the default password for a new account  in your database. If you need something more specific ,  like GUID ,  you would  better use an online generator . These are some simple practical examples :

// example 1
function generateRandom($c) {
$randomText = '';
$supportedCharacter = array('1','2','3','4','5','6','7','8','9',
'0','a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z',
'!','$','%');
for ($i = 1; $i <= $c; $i++) {
$position = mt_rand(0,sizeof($supportedCharacter) - 1);
$randomText .= $supportedCharacter[$position];
}

return $randomText;
}

echo  generateRandom("5") ;

// example 2
function generateRandom2($length = "")
{
	$code = md5(uniqid(rand(), true));
	if ($length != "") return substr($code, 0, $length);
	else return $code;
}

echo  generateRandom2("5") ;

//Example 3
function randPassword() {
$password = '';
$punct = array ("!", "#", "@", "|","%" ) ;
for ($x = 1; $x <= 8; $x++) {
switch ( rand(1, 4) ) {
//  Add a random digit, 0-9
case 1:
$password .= rand(0, 9);
break;
//  Add a random upper-case letter
case 2:
$password .= chr( rand(65, 90) );
break;
//  Add a random lower-case letter
case 3:
$password  .= chr( rand(97, 122) );
break;
	  case 4:
$password  .= $punct[rand(0, 3)];
break;
}
}
return $password;
}
echo "
".randPassword();

//example 4
// random number between $upper and $lower, inclusive
$random_number = mt_rand($lower, $upper);
Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s