OAuthProvider::generateToken
(PECL OAuth >= 1.0.0)
OAuthProvider::generateToken — 生成一个随机令牌
说明
final public static OAuthProvider::generateToken(int
$size
, bool $strong
= false): string生成一个伪随机字节的 字符串 。
参数
-
size
-
想要的令牌长度,单位为字节。
-
strong
-
设置为
true
则意味着将对熵使用/dev/random
,否则使用非阻塞的/dev/urandom
。在 Windows 平台将忽略此参数。
返回值
生成的令牌,一个以字节为单位的 字符串 。
错误/异常
如果 strong
参数为 true
, 则当回退到用 rand() 来实现填充剩余的随机字节的时候,将触发一个 E_WARNING
级别的错误(比如,当最初找不到足够的随机数据的时候)。
范例
示例 #1 OAuthProvider::generateToken() 例子
<?php
$p = new OAuthProvider();
$t = $p->generateToken(4);
echo strlen($t), PHP_EOL;
echo bin2hex($t), PHP_EOL;
?>
以上例程的输出类似于:
4 b6a82c27
注释
注意:
当系统没有足够的随机数据可用的时候,此函数将使用 PHP 内部的 rand() 来实现填充剩余的随机字节。
参见
- openssl_random_pseudo_bytes() - 生成一个伪随机字节串
- mcrypt_create_iv() - 从随机源创建初始向量

User Contributed Notes 1 note
carlosouza at me dot com ¶
10 years ago
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
备份地址:http://www.lvesu.com/blog/php/oauthprovider.generatetoken.php