1. 程式人生 > >生成隨機密碼,驗證碼

生成隨機密碼,驗證碼

PHP寫法:

//A-Z  a-z  0-9  !#$%^&*
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%^&*";
//生成隨機字元
function createPwd($str,$len){
    $pwd = '';
    $strlen = strlen($str);
    for($i=0;$i<$len;$i++){
        $pwd .= $str{mt_rand(0,$strlen-1)};
    }
    return $pwd;
}

echo createPwd($str,16);

js寫法

//A-Z  a-z  0-9  !#$%^&*
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%^&*";
//生成隨機字元
function createPwd(str,len){
    var pwd = '';
    var maxPos = str.length;
    for(var i=0;i<len;i++){
        pwd += str.charAt(Math.floor(Math.random()*maxPos));
    }
    return pwd;
}

var passwd = createPwd(str,16);
document.write(passwd);