Generating Random Passwords

Aug 28, 2010 Author: Developer

Random (but difficult-to-guess) strings are important in user security. For example, if someone loses a password and you're using MD5 hashes, you won't be able to, nor should you want to, look it up. Instead, you should generate a secure random password and send that to the user. Another application for random number generation is creating activation links in order to access your site's services. Here is a function that creates a password:

 function make_password($num_chars) {
    if ((is_numeric($num_chars)) &&
        ($num_chars > 0) &&
        (! is_null($num_chars))) {

        $password = '';
        $accepted_chars = 'abcdefghijklmnopqrstuvwxyz1234567890';

        // Seed the generator if necessary.
        srand(((int)((double)microtime()*1000003)) );

        for ($i=0; $i<=$num_chars; $i++) {
            $random_number = rand(0, (strlen($accepted_chars) -1));
            $password .= $accepted_chars[$random_number] ;

        return $password;

The make_password() function returns a string, so all you need to do is supply the length of the string as an argument:

$six_character_password = make_password(6);

views 8141
  1. Add New Comment