Random string help!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kaily
Forum Newbie
Posts: 12
Joined: Fri Jul 05, 2002 12:17 pm

Random string help!

Post by kaily »

I want to create a random srting as a password,which function I can use?
sorry for english! :oops:
User avatar
untouchable
Forum Newbie
Posts: 7
Joined: Sat Jul 06, 2002 11:41 pm

Post by untouchable »

Code: Select all

$string = rand(1,1000)
$string = md5($string);
super simple.
User avatar
RandomEngy
Forum Contributor
Posts: 173
Joined: Wed Jun 26, 2002 3:24 pm
Contact:

Post 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.
gnu2php
Forum Contributor
Posts: 122
Joined: Thu Jul 11, 2002 2:53 am

Post 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>";

?>
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post 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.
Post Reply