php 获取随机字符,php获取随机字符串

本文介绍了如何在PHP中安全地生成随机字符串,包括使用random_int()函数以及在PHP5中实现该功能的polyfill。文章提供了两个函数generateRandomString()和random_str()的示例代码,强调了在生产环境中安全生成随机数的重要性,并提醒开发者在部署前应咨询密码学专家。此外,还展示了这两个函数的实际应用例子。
摘要由CSDN通过智能技术生成

2629ec01820b11e8d54ca6fc12c22d57.png

PHP获取随机字符串实现代码如下:

function generateRandomString($length = 10) {

$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

$charactersLength = strlen($characters);

$randomString = '';

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

$randomString .= $characters[rand(0, $charactersLength - 1)];

}

return $randomString;

}

输出随机字符串,调用方式如下:

// Echo the random string.

// Optionally, you can give it a desired string length.

echo generateRandomString();

这个问题有很多答案,但是没有一个可以利用加密安全的伪随机数生成器。

对于那些坚持自己发明解决方案的人,PHP 7.0.0将提供random_int();如果你还在用PHP 5。我们为random_int()写了一个PHP 5的polyfill,这样在升级到PHP 7之前就可以使用新的API了。

在PHP中安全地生成随机整数并不是一项简单的任务。在将自行开发的算法部署到生产环境之前,您应该始终与您的常驻StackExchange密码专家进行检查。

有了安全的整数生成器后,使用CSPRNG生成随机字符串就变的简单。

/**

* Generate a random string, using a cryptographically secure

* pseudorandom number generator (random_int)

*

* This function uses type hints now (PHP 7+ only), but it was originally

* written for PHP 5 as well.

*

* For PHP 7, random_int is a PHP core function

* For PHP 5.x, depends on https://github.com/paragonie/random_compat

*

* @param int $length How many characters do we want?

* @param string $keyspace A string of all possible characters

* to select from

* @return string

*/

function random_str(

int $length = 64,

string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

): string {

if ($length < 1) {

throw new \RangeException("Length must be a positive integer");

}

$pieces = [];

$max = mb_strlen($keyspace, '8bit') - 1;

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

$pieces []= $keyspace[random_int(0, $max)];

}

return implode('', $pieces);

}

使用

$a = random_str(32);

$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');

$c = random_str();

原创文章,作者:犀牛前端部落,如若转载,请注明出处:https://www.pipipi.net/4519.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值