php 生成(伪)随机字母数字字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48124/
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
Generating (pseudo)random alpha-numeric strings
提问by UnkwnTech
How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
如何在 PHP 中生成(伪)随机字母数字字符串,例如:'d79jd8c'?
回答by Jeremy Ruten
First make a string with all your possible characters:
首先用所有可能的字符创建一个字符串:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range()to do this more quickly.
您还可以使用range()更快地执行此操作。
Then, in a loop, choose a random number and use it as the index to the $charactersstring to get a random character, and append it to your string:
然后,在循环中,选择一个随机数并将其用作$characters字符串的索引以获取随机字符,并将其附加到您的字符串中:
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
$random_string_lengthis the length of the random string.
$random_string_length是随机字符串的长度。
回答by azerafati
I like this function for the job
我喜欢这个工作的功能
function randomKey($length) {
$pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $pool[mt_rand(0, count($pool) - 1)];
}
return $key;
}
echo randomKey(20);
回答by emix
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytesfunction:
使用openssl_random_pseudo_bytes函数生成加密强度高的随机(可能)8 字符字符串:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
程序方式:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
更新:
PHP7 introduced the random_x()functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compatlibrary which is a polyfill for random_bytes()and random_int()from PHP 7.
PHP7引入了random_x()应该更好的功能。如果您来自 PHP 5.X,请使用优秀的paragonie/random_compat库,它是PHP 7 中random_bytes()和random_int() 的 polyfill。
function randomString($length)
{
return bin2hex(random_bytes($length));
}
回答by Marco Panichi
One line solution:
一行解决方案:
echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );
You can change the substr parameter in order to set a different length for your string.
您可以更改 substr 参数以便为您的字符串设置不同的长度。
回答by diegoiglesias
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
我知道这是一篇旧帖子,但我想为我根据 Jeremy Ruten 的回答创建的课程做出贡献,并通过评论中的建议进行改进:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
回答by Daniel
Use the ASCII tableto pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
使用ASCII 表选择一系列字母,其中: $range_start , $range_end 是来自 ASCII 表中十进制列的值。
I find that this method is nicer compared to the method describedwhere the range of characters is specifically defined within another string.
我发现这种方法与描述的在另一个字符串中明确定义字符范围的方法相比更好。
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
查看更多:
回答by David Young
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
简单的家伙.... 但请记住,每个字节都是 0 到 255 之间的随机数,这对于随机字符串就可以了。还要记住,您将有两个字符来表示每个字节。
$str = bin2hex(random_bytes(32)); // 64 character string returned
回答by Peter
I have made the following quick function just to play around with the range()function. It just might help someone sometime.
我做了以下快速功能只是为了玩这个range()功能。它可能会在某个时候帮助某人。
Function pseudostring($length = 50) {
// Generate arrays with characters and numbers
$lowerAlpha = range('a', 'z');
$upperAlpha = range('A', 'Z');
$numeric = range('0', '9');
// Merge the arrays
$workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
$returnString = "";
// Add random characters from the created array to a string
for ($i = 0; $i < $length; $i++) {
$character = $workArray[rand(0, 61)];
$returnString .= $character;
}
return $returnString;
}
回答by Edward Fuller
Maybe I missed something here, but here's a way using the uniqid() function.
也许我在这里错过了一些东西,但这里有一种使用 uniqid() 函数的方法。
回答by Molla Rasel
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 generateRandomString();

