User login

Creating a random password... the Drupal way

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.

Resolution

Searched words: 
make random password generate pass assorted string of letters php random password generator

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.