Random password generator component for CakePHP

In: Tutorials

11 Jun 2008

This is a component I put together for CakePHP 1.2 RC1 that will generate a random password. All you have to pass it is the length of the password.

To use it, make this file app/controllers/components/password_helper.php

You can use it in a controller by adding ‘PasswordHelper’ to the $components array.

You can adjust the $possible set with your desired characters.

Here is the code:

<?php
class PasswordHelperComponent extends Object {
 
/**
 * Password generator function
 *
 * This function will randomly generate a password from a given set of characters
 *
 * @param int = 8, length of the password you want to generate
 * @return string, the password
 */    
    function generatePassword ($length = 8)
    {
        // initialize variables
        $password = "";
        $i = 0;
        $possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
 
        // 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++;
            }
        }
        return $password;
    }
}
?>

1 Response to Random password generator component for CakePHP

Avatar

Frank

August 31st, 2008 at 4:21 am

Thanks for this man, nice little helper.

Comment Form

SoliTech GmbH

Services such as Facebook, MySpace, LinkedIn, Twitter etc. are experiencing exponential growth. Your company needs to stay competitive and utilize this new technology. We will help you devise and execute a higly effective marketing strategy that will grow your brands' following and deliver measurable results.

Click here to see all our service.