James Linden

~# data ninja / linux guru / web dev geek / robotics nerd / idea machine / N6NRD

Code / Random Password Generator for PHP

Random Password Generator for PHP

Overview

The Random Password Generator for PHP is a simple PHP function for generating passwords of varying lengths using random characters.

Environment

  • Any
  • PHP 5.3 +

Code

function genrandpass( $length, $punc = false ) {
    $c = (bool)$punc ? array( '~', '!', '@', '#', '$', '^', '&', '(', ')', '-', '_', '[', ']', '{', '}', '?', ':', ';', '.', ',' ) : array();
    $x = range( 0, 9 );
    $c = array_merge( $c, $x, range( 'a', 'z' ), $x, range( 'A', 'Z' ) );
    shuffle( $c );
    $y = count( $c ) - 1;
    $p = $z = null;
    while( strlen( $p ) < (int)$length ) {
        $x = rand( 0, $y );
        if( $x != $z ) {
            $p .= $c[ $x ];
            $z = $x;
        }
    }
    return $p;
}

Howto

Simply call the function:

$mypass = genrandpass(14);

This will output something like:

Lh15Lsm0OYFj0q

If you want to include punctuation in the output string:

$mypass = genrandpass(14,true);

Which will output something like:

VN~7Ws8x52Y;02

License

This project is BSD (2 clause) licensed.

photo of James Linden
Founder / Head Geek
Digital Dock, LLC
aka kodekrash & N6NRD
Alexandria, LA USA

What I Do

Linux administration & virtualization
Data mining, storage & analysis
Web development

What I've Done

Rescued a skunk
Built Prime GNU/Linux
Contributed to Spidering Hacks