d
Amit DhamuSoftware Engineer
 

Generate Random Password

2 minute read 00000 views
// Function
function createRandomPassword($type, $length, $punc) {
    switch ($type) {
        case 'alpha':
            $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 'numeric':
            $chars = '23456789';
            break;
        case 'alphanumeric':
            $chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ023456789';
            break;
    }

    if ($punc) {
        $chars .= '!$%^*()?#~@[]{}|+=-_';
    }

    srand((double)microtime()*1000000);

    $i = 0;
    $pass = '';

    while ($i < $length) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}

// Usage - creates an alpha only 6 character password without punctuation
createRandomPassword('alpha', 6, false)