下面的方法可以生成随机数或者字符串,看代码:

    /**

     * @static

     *

     * @param      $length  想要的长度

     * @param bool $numeric  想要随机字符还是随机数,false-字符串,true-数字

     *

     * @return string

     */

    static public function random($length, $numeric = false) {

        if((boolean)$numeric) {

            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));

        } else {

            $hash = '';

            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';

            $max = strlen($chars) - 1;

            for($i = 0; $i < $length; $i++) {

                $hash .= $chars[mt_rand(0, $max)];

            }

        }

        return $hash;

    }

 

对以上方法中用到的函数做一解释:

1、sprintf() 函数把格式化的字符串写写入一个变量中。例如例子中用到的:

sprintf('%05d', mt_rand(0, 999);就是在0-999之间随机取一个数,不够5位的前面补0。

2、mt_rand() 随机取出一个整数。

3、pow(x,y) 返回x的y次幂。

4、strlen()字符串的长度。

5、如果一个字符串$str = 'abc';那么$str[0] = 'a', $str[1] = 'b', $str[2] = 'c'。