<?php
/**
 *  获取随机密码函数
 *  @param string $type 密码字符串类型
 *  @param string $customStr 自定义密码组成字符
 *  @param int    $length 密码长度
 *  @param string $splitChar 分隔符,默认不分隔
 *  @param int    $splitLength 密码字符分隔长度 比如:密码为abc-def-ghi时$splitLength = 3
 *
 */
function getPassword($type 'number-lower-upper'$customStr ''$length 32$splitChar ''$splitLength 4) {
    
$strArr         = array(
        
'number'    => '0123456789',
        
'lower'     => 'abcdefghijklmnopqrstuvwxyz',
        
'upper'     => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        
'special'   => '~!@#$%^&*()_+{}|[]\-=:<>?/',
    );
     
    if(
$type == 'all') {        //全部
        
$str implode(''$strArr);
    } else if(
$type == 'custom') {        //自定义类型
        
if(empty($customStr)) {    //未填写自定义类型,则默认为数字+大小写字母
            
$type    'number-lower-upper';
        } else {
            
$str     $customStr;
        }
    }
     
    
//custom 没带自定义类型 或 其他类型
    
if(empty($str)) {
        
$typeParts  explode('-'$type);
        
$str        '';
        foreach(
$typeParts as $part) {
            
$str   .= $strArr[$part];
        }
    }
     
    
$maxLength         32;    //最大长度
    
$length            = empty($length) ? $maxLength min((int)$length$maxLength);
    if(empty(
$length)) {
        
$length $maxLength;
    }
    
    
$splitLength max(1, (int)$splitLength);
     
    
// 大数据下面str_shuffle会导致随机种子耗尽而导致结果循环(错误做法)
    // $passwordStr    = '';
    // do {
        // $randStr        = str_shuffle($str);
        // $passwordStr   .= substr($randStr, 0, 1);        //每次取一个字符
        // $passwordLength = strlen($passwordStr);
    // } while($passwordLength < $length);
     
    //纠正
    
$passwordStr    '';
    
$strMaxIndex    strlen($str) - 1;
    do {
        
$randIndex      mt_rand(0$strMaxIndex);
        
$passwordStr   .= $str[$randIndex];        //每次取一个字符
        
$passwordLength strlen($passwordStr);
    } while(
$passwordLength $length);
     
    
//需要分隔
    
if($splitChar != '') {
        
$passwordStr implode($splitCharstr_split($passwordStr$splitLength));
    }
    return 
$passwordStr;
}

/**
 * 获取多个密码
 * @param string $times 密码个数
 * @param string $type
 * @param string $customStr
 * @param int    $length
 * @param string $splitChar
 * @param int    $splitLength
 * @param int    $times
 *
 * @return string
 */
function getMorePassword($times 1$type 'number-lower-upper'$customStr ''$length 32$splitChar ''$splitLength 4) {
    
$passwords = [];
    for( 
$i 1$i $times$i++ ) {
        
$passwords[] = getPassword($type$customStr$length$splitChar$splitLength);
    }
    
    return 
implode("\n"$passwords);
}