Using PHP to generate random passwords

December 27th 2012

In all my authentication systems, I've implemented the functionality to generate a temporary password. This comes in handy when a user forgets their password and they need to be emailed a new one.

When I generate a password, I avoid common the similar characters (such as o and 0, 1 and l etc etc.)

So, here's the class I created to manage my Random Password generation in PHP.

PHP Code:
<?php
class App_Data_Password {

    
/**
     * Retrieve the next character while ensuring no duplication of characters
     * next to each other
     * @param string $haystack
     * @param string $previousCharacter
     * @return string
     */
    
private function randomNotSame($haystack$previousCharacter) {
        
$maxKey = (count($haystack) - 1);
        
$key rand(0$maxKey);
        
$nextChar $haystack[$key];
        if (
$nextChar == $previousCharacter) {
            return 
$this->randomNotSame($haystack$previousCharacter);
        }
        return 
$nextChar;
    }

    
/**
     * Generate and return a randomly generated password
     * complete with Alpha, Numeric, Special
     *
     * @param integer $length
     * @return string
     */
    
public function generate($length 9)
    {
        if (!
is_numeric($length)) {
            
$length 9;
        }
        else {
            
$length = (int)$length;
        }
        
$lowerAZ = array("a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z");
        
$upperAZ = array("A","B","C","D","E","F","G","H","J","K","M","N","P","Q","R","S","T","U","V","W","X","Y","Z");
        
$punctuation = array(",",".");
        
$special = array(';',"!","@","(",")","[","]","-","=","/","\\","*","%");

        
$full array_merge(array_merge($lowerAZ$upperAZ),array_merge($punctuation$special));

        
$maxKey = (count($full) - 1);
        
$str "";
        
$i 0;
        
$previousChar "";
        while (
$i $length) {
            
$i++;
            
$next $this->randomNotSame($full$previousChar);
            
$str .= $next;
            
$previousChar $next;
        }
        return 
$str;

    }

    
/**
     * Generate and return a randomly generated password
     * complete with Alpha, Numeric, Special
     *
     * @param integer $length
     * @return string
     */
    
public static function generateStatic($length 9)
    {
        
$class = new self();
        return 
$class->generate($length);
    }

}

Using the PHP Random Password Generator is easy. You can call it in 2 ways.

You can either call it in the traditional object initialisation method, or via static.

PHP Code:
<?php
$cl 
= new App_Data_Password();
$password $cl->generate(9);

Here's the static way:

PHP Code:
<?php
$password 
App_Data_Password::generateStatic(9);

Either way, you'd end up with a randomly generated password that's 9 characters in length.

I hope you find this helpful, it's a great addition to your class library.