文字

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken生成一个随机令牌

说明

final public static string OAuthProvider::generateToken ( int $size [, bool $strong = false ] )

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

参数

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() 来实现填充剩余的随机字节。

参见

  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • mcrypt_create_iv() - 从随机源创建初始向量

用户评论:

[#1] carlosouza at me dot com [2012-03-28 14:32:35]

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

上一篇: 下一篇: