首頁 > 易卦

PHP生成隨機數的方法總結

作者:由 七七小影視 發表于 易卦日期:2022-01-26

c語言怎麼取隨機數

1,mt_rand()

function GetRandStr($length){ $str=‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’; $len=strlen($str)-1; $randstr=‘’; for($i=0;$i<$length;$i++){ $num=mt_rand(0,$len); $randstr 。= $str[$num]; } return $randstr;}

$number=GetRandStr(6);echo $number;

2,

function make_password( $length = 8 ){ // 密碼字符集,可任意新增你需要的字元 $chars = array(‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’,‘i’, ‘j’, ‘k’, ‘l’,‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’,‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’,‘z’, ‘A’, ‘B’, ‘C’, ‘D’,‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’,‘M’, ‘N’, ‘O’,‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’,‘Z’,‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘!’,‘@’,‘#’, ‘$’, ‘%’, ‘^’, ‘&’, ‘*’, ‘(’, ‘)’, ‘-’, ‘_’,‘[’, ‘]’, ‘{’, ‘}’, ‘<’, ‘>’, ‘~’, ‘`’, ‘+’, ‘=’, ‘,’,‘。’, ‘;’, ‘:’, ‘/’, ‘?’, ‘|’); // 在 $chars 中隨機取 $length 個數組元素鍵名 $keys = array_rand($chars, $length); $password = ‘’; for($i = 0; $i < $length; $i++){ // 將 $length 個數組元素連線成字串 $password 。= $chars[$keys[$i]]; } return $password;}

3,取當時時間戳

function get_password( $length = 8 ){ $str = substr(md5(time()), 0, $length); //md5加密,time()當前時間戳 return $str;}

4,打亂字串

function getrandstr(){ $str=‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890’; $randStr = str_shuffle($str);//打亂字串 $rands= substr($randStr,0,6);//substr(string,start,length);返回字串的一部分 return $rands; }