Page 1 of 1

Random string help!

Posted: Wed Jul 10, 2002 9:51 pm
by kaily
I want to create a random srting as a password,which function I can use?
sorry for english! :oops:

Posted: Wed Jul 10, 2002 11:28 pm
by untouchable

Code: Select all

$string = rand(1,1000)
$string = md5($string);
super simple.

Posted: Thu Jul 11, 2002 10:32 am
by RandomEngy
With that, all the passwords will turn out to be something like 288cc0ff022877bd3df94bc9360b9c5d . That would be highly annoying, so you could change untouchable's code to give only the first few digits of the md5() number:

Code: Select all

$pass = substr(md5(rand(1,1000)),0,8);
If you wanted an 8-character password. Although the problem is still that you only use 0-9 and a-f. I'm not sure how you'd make a script that used a-z as well.

Posted: Thu Jul 11, 2002 9:10 pm
by gnu2php
One option is to create an array of human-readable keywords and have one be randomly selected. Then append some numbers to the end of the keyword. This would make the password much easier for people to use.

For example:

Code: Select all

<?php // This creates a random password in the form KEYWORD#### (where #### is a 4-digit number)

// Enter a long list of keywords here:
$keywords = array('some_keyword', 'foo', 'hello', 'world', 'php', 'lemonpony', 'gnu2php');

$num_keywords = count($keywords);

// Options:
$MIN_PW = 1000;
$MAX_PW = 9999;


function make_seed() // Got this from http://www.php.net/manual/en/function.srand.php
&#123;
	list($usec, $sec) = explode(' ', microtime());
	return (float) $sec + ((float) $usec * 100000);
&#125;
srand(make_seed());


// Generate the password
$my_password = $keywords&#1111;rand(0, ($num_keywords - 1))].rand($MIN_PW, $MAX_PW);

print "The password is <b>$my_password</b>";

?>

Posted: Thu Jul 11, 2002 10:44 pm
by jason
Here is a function I use on my site to randomly generate passwords from 6 to 12 characters long:

Code: Select all

<?php 
function update_user_password () 
&#123; 
    $seed = (integer) md5(time()); 
    mt_srand($seed); 
    $password = mt_rand(1,99999999); 
    $password = substr(md5($password), mt_rand(0, 19), mt_rand(6, 12)); 
    return $password; 
&#125; 
?>
Just call it, and it returns a random password.