Creating a random password... the Drupal way

Key words and phrases: 
make random password generate pass assorted string of letters php random password generator
Description & Info: 

Lesson of the day: don't reinvent Drupal functions.

<?php
/**
* Generate a really lame random password.  This would be cooler with words.
*
* Still, gratitude to Jon Haworth, from whom this code was taken.
* <a href="http://www.laughing-buddha.net/jon/php/password/
" title="http://www.laughing-buddha.net/jon/php/password/
">http://www.laughing-buddha.net/jon/php/password/
</a> */
function changents_tl_au_rand_password($length = 5) {
 
// start with a blank password
 
$password = "";

 
// define possible characters
 
$possible = "23456789abcdefghijkmnpqrstuvwxyz";
   
 
// 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;  
}
?>

Practically the same result - and almost the exact code - as Drupal's own user_password function. (Haworth's code does have a step to prevent a letter from being used twice, but I was considering taking that out anyway.)

http://api.drupal.org/api/function/user_password/5

So we'll just use that, and pass in the shorter length we want.

by Benjamin Melançon
Posted on Sun, 2008-06-01 05:23
in
Post new comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <small> <pre> <strike> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.