Breadcrumbs

Generating Random Passwords

Do you want to create a random password script, either to generate a new password when the user forgets it, or to make an account activation script? This script can be used to for many tasks and is written in PHP.

You could even expand on this script and simply include capital letters in a PHP string and make the password CaSe sensitive.

Below is the code for the random password generator, the explanations are in the comments:

Code: PHP

<?php
/*
Created on 26/10/04
Please leave this credit in. Script submitted to www.reversedlogic.net /
www.lowter.com
MADE MY MATTHEW DURNAN - CLEARPHP.COM
Modified 22/12/04 by MATTHEW DURNAN with changes suggested by laserlight
*/

function makepass($len 8) { // This begins the function
    /* Characters that could be chosen, you could include caps and then make the password case sensitive as well */
    
$str 'abcdefghijklmnopqrstuvwxyz0123456789';
    
    
/*This counts the number of characters in $str - 1, as when using mt_rand it also includes zero */
    
$max strlen($str) - 1;
    
$pass '';
    
    
/* Generates the password by adding a character each time */
    
for ($i 0$i $len$i++) {
        
/* This generates a new character and then adds the generated character to the existing string */
        
$pass .= $str{mt_rand(0$max)};
    }
    
    return 
$pass// Prints the password
}
?>

To call and echo (print) out the function you simply could use:

Code: PHP

<?php
echo makepass(); // Generates a password 8 characters long
?>

Or if you wanted to define the number of characters you could use:

Code: PHP

<?php
echo makepass('10'); // Generates a password 10 characters long
?>