Write a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9) [closed]

I think you’re looking for the tag.

In the spirit of helping others I’ll post a commented solution. However, keep in mind the only way to get better is to try first, ask questions later. That is to say, make an attempt then ask others where you went wrong.

Example/Demo:

/**
 * Generate a password N characters long consisting of characters
 *
 * @param int $size
 * @param string $characters
 * @param callback $random (optional) source of random, a function with two parameters, from and to
 * @return string|NULL password
 */
function generate_password($size, $characters, $random = 'rand') {

    // validate $size input
    $size = (int) $size;

    if ($size <= 0) {
        trigger_error(sprintf('Can not create a password of size %d. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    if ($size > 255) {
        trigger_error(sprintf('Refused to create a password of size %d as this is larger than 255. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    // normalize $characters input, remove duplicate characters
    $characters = count_chars($characters, 3);

    // validate number of characters
    $length = strlen($characters);
    if ($length < 1) {
        trigger_error(sprintf('Can not create a random password out of %d character(s). [%s]', $length, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }

    // initialize the password result
    $password = str_repeat("\x00", $size);

    // get the number of characters minus one
    // your string of characters actually begins at 0 and ends on the
    // string-length - 1:
    //   $characters[0] = 'a'
    //   $characters[1] = 'b'
    //   $characters[2] = 'c'
    $length--;

    // get one random character per each place in the password
    while ($size--)
    {
        // generate a random number between 0 and $length (including)
        $randomValue = $random(0, $length);
        // that random number is used to turn the number into a character
        $character = $characters[$randomValue];
        // set the random character
        $password[$size] = $character;
    }

    // return the result
    return $password;
}

Leave a Comment