php生成随机数或字符串的例子

发布时间:2020-07-13编辑:脚本学堂
在php中怎么生成随机数或随机字符串?这里分享一例php代码,学习下php随机数的生成方法,需要的朋友参考下。

利用php生成随机数随机字符串的函数,.$chars变量中的字符自行修改,即可达到数字或字符串的目的。

专题推荐:php随机数

例子:
 

复制代码 代码示例:
<?php
/**
* 产生随机字符串
*
* 产生一个指定长度的随机字符串,并返回给用户
*
* @access public
* @param int $len 产生字符串的位数
* @return string
*/
function randstr($len=6) {
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz0123456789-@#~';
// characters to build the password from
mt_srand((double)microtime()*1000000*getmypid());
// seed the random number generater (must be done)
$password='';
while(strlen($password)<$len)
$password.=substr($chars,(mt_rand()%strlen($chars)),1);
return $password;
}