• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • OAuthProvider::generateToken()

    (PECL OAuth >= 1.0.0)

    生成一个随机令牌

    说明

    finalpublicstaticOAuthProvider::generateToken(int $size[,bool $strong= false]): string

    生成一个伪随机字节的字符串。

    参数

    $size

    想要的令牌长度,单位为字节。

    $strong

    设置为TRUE则意味着将对熵使用/dev/random,否则使用非阻塞的/dev/urandom。在 Windows 平台将忽略此参数。

    返回值

    生成的令牌,一个以字节为单位的字符串。

    错误/异常

    如果$strong参数为TRUE,则当回退到用rand()来实现填充剩余的随机字节的时候,将触发一个E_WARNING级别的错误(比如,当最初找不到足够的随机数据的时候)。

    范例

    Example #1 OAuthProvider::generateToken()例子

    <?php
    $p = new OAuthProvider();
    $t = $p->generateToken(4);
    echo strlen($t),  PHP_EOL;
    echo bin2hex($t), PHP_EOL;
    ?>
    

    以上例程的输出类似于:

    4
    b6a82c27
    

    注释

    Note:

    当系统没有足够的随机数据可用的时候,此函数将使用 PHP 内部的rand()来实现填充剩余的随机字节。

    参见

    Be careful when setting the 'strong' parameter to true.
    If you system doesn't have enough entropy your script will block which can cause timeouts in other parts of your code.
    In my case, the most serious symptom was my script blocking when trying to read from /dev/random and causing a 'MySQL has gone away' error.
    Hopefully this saves someone the trouble when deciding to use /dev/random entropy