php PHP随机字符串生成器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4356289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP random string generator
提问by Captain Lightning
I'm trying to create a randomized string in PHP, and I get absolutely no output with this:
我正在尝试在 PHP 中创建一个随机字符串,但我绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
What am I doing wrong?
我究竟做错了什么?
回答by Stephen Watkins
To answer this question specifically, two problems:
具体回答这个问题,有两个问题:
$randstring
is not in scope when you echo it.- The characters are not getting concatenated together in the loop.
$randstring
当您回显时不在范围内。- 字符没有在循环中连接在一起。
Here's a code snippet with the corrections:
这是带有更正的代码片段:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Output the random string with the call below:
使用以下调用输出随机字符串:
// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.
请注意,这会生成可预测的随机字符串。如果要创建安全令牌,请参阅此答案。
回答by A. Cheshirov
Note:
str_shuffle()
internally usesrand()
, which is unsuitable for cryptography purposes (e.g. generating random passwords). You want a secure random number generatorinstead. It also doesn't allow characters to repeat.
注意:
str_shuffle()
内部使用rand()
,它不适合加密目的(例如生成随机密码)。您需要一个安全的随机数生成器。它也不允许字符重复。
One more way.
还有一种方式。
UPDATED(now this generates any length of string):
更新(现在生成任意长度的字符串):
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
echo generateRandomString(); // OR: generateRandomString(24)
That's it. :)
就是这样。:)
回答by Scott Arciszewski
There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator(CSPRNG).
这个问题有很多答案,但没有一个利用加密安全伪随机数生成器(CSPRNG)。
The simple, secure, and correct answer is to use RandomLiband don't reinvent the wheel.
简单、安全和正确的答案是使用RandomLib并且不要重新发明轮子。
For those of you who insist on inventing your own solution, PHP 7.0.0 will provide random_int()
for this purpose; if you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int()
so you can use the new API even before you upgrade to PHP 7.
对于那些坚持发明自己的解决方案的人,PHP 7.0.0 将random_int()
为此提供;如果您仍在使用 PHP 5.x,我们为random_int()
您编写了一个PHP 5 polyfill,因此您甚至可以在升级到 PHP 7 之前使用新的 API。
Safely generating random integers in PHPisn't a trivial task. You should always check with your resident StackExchange cryptography expertsbefore you deploy a home-grown algorithm in production.
在 PHP 中安全地生成随机整数并不是一项简单的任务。在生产中部署本土算法之前,您应该始终与常驻 StackExchange 加密专家进行核对。
With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.
有了安全的整数生成器,用 CSPRNG 生成随机字符串就像在公园里散步一样。
Creating a Secure, Random String
创建安全的随机字符串
/**
* 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);
}
Usage:
用法:
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
Demo: https://3v4l.org/IMJGF(Ignore the PHP 5 failures; it needs random_compat)
演示:https: //3v4l.org/IMJGF(忽略 PHP 5 失败;它需要 random_compat)
回答by Rudie
This creates a 20 character long hexadecimal string:
这将创建一个 20 个字符长的十六进制字符串:
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
In PHP 7 (random_bytes()):
在 PHP 7 中(random_bytes()):
$string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
// or
$string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
// or
$string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f
回答by Humphrey
@tasmaniski: your answer worked for me. I had the same problem, and I would suggest it for those who are ever looking for the same answer. Here it is from @tasmaniski:
@tasmaniski:你的回答对我有用。我遇到了同样的问题,我会建议那些一直在寻找相同答案的人。这是来自@tasmaniski:
<?php
$random = substr(md5(mt_rand()), 0, 7);
echo $random;
?>
Here is a youtube video showing us how to create a random number
回答by rjmunro
Depending on your application (I wanted to generate passwords), you could use
根据您的应用程序(我想生成密码),您可以使用
$string = base64_encode(openssl_random_pseudo_bytes(30));
Being base64, they may contain =
or -
as well as the requested characters. You could generate a longer string, then filter and trim it to remove those.
作为 base64,它们可能包含=
或-
以及请求的字符。您可以生成更长的字符串,然后对其进行过滤和修剪以删除它们。
openssl_random_pseudo_bytes
seems to be the recommended way way to generate a proper random number in php. Why rand
doesn't use /dev/random
I don't know.
openssl_random_pseudo_bytes
似乎是在 php 中生成适当随机数的推荐方式。为什么rand
不使用/dev/random
我不知道。
回答by Kraang Prime
Here is a simple one-liner that generates a true random string without any script level looping or use of OpenSSL libraries.
这是一个简单的单行代码,它生成一个真正的随机字符串,无需任何脚本级循环或使用 OpenSSL 库。
echo substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', mt_rand(1,10))), 1, 10);
To break it down so the parameters are clear
分解它,使参数清晰
// Character List to Pick from
$chrList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Minimum/Maximum times to repeat character List to seed from
$chrRepeatMin = 1; // Minimum times to repeat the seed string
$chrRepeatMax = 10; // Maximum times to repeat the seed string
// Length of Random String returned
$chrRandomLength = 10;
// The ONE LINE random command with the above variables.
echo substr(str_shuffle(str_repeat($chrList, mt_rand($chrRepeatMin,$chrRepeatMax))), 1, $chrRandomLength);
This method works by randomly repeating the character list, then shuffles the combined string, and returns the number of characters specified.
此方法的工作原理是随机重复字符列表,然后对组合字符串进行打乱,并返回指定的字符数。
You can further randomize this, by randomizing the length of the returned string, replacing $chrRandomLength
with mt_rand(8, 15)
(for a random string between 8 and 15 characters).
您可以通过随机化返回字符串的长度来进一步随机化,替换$chrRandomLength
为mt_rand(8, 15)
(对于 8 到 15 个字符之间的随机字符串)。
回答by Davor
function generateRandomString($length = 15)
{
return substr(sha1(rand()), 0, $length);
}
Tada!
多田!
回答by Rathienth Baskaran
A better way to implement this function is:
实现此功能的更好方法是:
function RandomString($length) {
$keys = array_merge(range(0,9), range('a', 'z'));
$key = "";
for($i=0; $i < $length; $i++) {
$key .= $keys[mt_rand(0, count($keys) - 1)];
}
return $key;
}
echo RandomString(20);
mt_rand
is more random according to thisand thisin PHP 7. The rand
function is an alias of mt_rand
.
回答by BoltClock
$randstring
in the function scope is not the same as the scope where you call it. You have to assign the return value to a variable.
$randstring
函数作用域中的作用域与您调用它的作用域不同。您必须将返回值分配给变量。
$randstring = RandomString();
echo $randstring;
Or just directly echo the return value:
或者直接回显返回值:
echo RandomString();
Also, in your function you have a little mistake. Within the for loop, you need to use .=
so each character gets appended to the string. By using =
you are overwriting it with each new character instead of appending.
另外,在你的函数中你有一个小错误。在 for 循环中,您需要使用,.=
以便将每个字符附加到字符串。通过使用,=
您将使用每个新字符覆盖它而不是附加。
$randstring .= $characters[rand(0, strlen($characters))];