MENU

PHP随机数生成畅想

August 19, 2016 • PHP

说明

在开发中常常会用到生成一些随机密码推荐码以及一些随机数等等。那么我在开发的过程中用过很多种方法。有基于时间戳随机函数以及UUID等等一些方法。这篇是对于目前已经用过或者学习到的一些小例子的整理,方便以后用到的时候可以快速的查阅。

示例


  • openssl_random_pseudo_bytes
    此函数返回指定长度的字节流,然后可以使用bin2hex转换为16进制的字符串.此函数需要安装对应的php-openssl扩展,不过一般的php环境都会安装这个扩展

    echo bin2hex(openssl_random_pseudo_bytes(16));
    //output: 969ed13182e00505dbbcb8550659b4d7

  • file_get_contents
    对于Linux系统来说这个可以直接读取Linux系统运行时的运行文件来获取一个UUID

    echo file_get_contents('/proc/sys/kernel/random/uuid');
    // 输出: 6c509fc7-328b-4d82-9af8-60c44e7b84b4

  • 字符池随机
    也就是把一些字符串加入到一个池中,然后循环的方式从里面随机挑选进行组合生成。

        function randomkeys($length)
        {
            $pattern = '1234567890abcdefghijklmnopqrstuvwxyz
                        ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&l
                        t;>?;#:@~[]{}-_=+)(*&^%$£"!';    //字符池
            for($i=0;$i<$length;$i++)
            {
                $key .= $pattern{mt_rand(0,35)};    //生成php随机数
            }
            return $key;
        }
        echo randomkeys(8);

    另一种方法稍微做了些修改,利用chr()函数已经ASCII表,省去创建字符池的步骤。

        function randomkeys($length)
        {
            $output='';
            for ($a = 0; $a < $length; $a++) {
                $output .= chr(mt_rand(33, 126));    //可以参看ASCII表设置字符的范围
            }
            return $output;
        }
        echo randomkeys(8);

    上面2个函数功能一样,只是第二个更加的简洁


  • 邀请码
    在之前的开发中生成一个邀请码的需求,要求数字加字母,参考了一些别人的推荐码都是数字 大小写字母 长度一般在8-10位左右,比如R5a7Qed3

        passwordChar = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $passwordLength = 8;
        $max = strlen($passwordChar) - 1;
        $password = '';
        for ($i = 0; $i < $passwordLength; ++$i) {
            $password .= $passwordChar[mt_rand(0, $max)];
        }
        echo $password;
        //possible output: 7dgG8EHu

文章参考

https://segmentfault.com/a/1190000004182573

类库参考

https://github.com/paragonie/random_compat
这个库提供了只有在PHP7上才有的随机函数random_intrandom_bytes,如果你想在PHP5中使用这2个函数那么可以使用这个库

https://gist.github.com/dahnielson/508447
一个github上别人写的UUID v3 v4 v5生成类

http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid
http://qa.helplib.com/296097 翻译的版本
这里面也是一些生成UUID的方法,有些可以借鉴一下

https://github.com/ramsey/uuid
依然是个生成UUID的库

http://hashids.org/
新发现的,待研究
Last Modified: November 10, 2019