php 生成随机 5 个字符的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5438760/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:24:33  来源:igfitidea点击:

Generate random 5 characters string

phprandom

提问by Peter

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.

我想创建精确的 5 个随机字符串,并且复制的可能性最小。最好的方法是什么?谢谢。

回答by Brad Christie

$rand = substr(md5(microtime()),rand(0,26),5);

Would be my best guess--Unless you're looking for special characters, too:

将是我最好的猜测——除非你也在寻找特殊字符:

$seed = str_split('abcdefghijklmnopqrstuvwxyz'
                 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 .'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

Example

例子

And, for one based on the clock (fewer collisions since it's incremental):

并且,对于基于时钟的一个(由于它是增量的,因此冲突较少):

function incrementalHash($len = 5){
  $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  $base = strlen($charset);
  $result = '';

  $now = explode(' ', microtime())[1];
  while ($now >= $base){
    $i = $now % $base;
    $result = $charset[$i] . $result;
    $now /= $base;
  }
  return substr($result, -5);
}

Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")

注意:增量意味着更容易猜测;如果您将其用作盐或验证令牌,请不要使用。“WCWyb”的盐(现在)意味着从现在起 5 秒它是“WCWyg”)

回答by Matthew

If forloops are on short supply, here's what I like to use:

如果for循环供不应求,这是我喜欢使用的:

$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);

回答by John Parker

A speedy way is to use the most volatile characters of the uniqidfunction.

一种快速的方法是使用uniqid函数中最易变的字符。

For example:

例如:

$rand = substr(uniqid('', true), -5);

回答by Apurba Pathak

You can try it simply like this:

您可以像这样简单地尝试一下:

$length = 5;

$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);

more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25

更多详情:http: //forum.arnlweb.com/viewtopic.php?f=7&t=25

回答by Archimedix

The following should provide the least chance of duplication (you might want to replace mt_rand()with a better random number source e.g. from /dev/*randomor from GUIDs):

以下应该提供最少的重复机会(您可能希望mt_rand()用更好的随机数源替换,例如来自/dev/*random或来自 GUID):

<?php
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $result = '';
    for ($i = 0; $i < 5; $i++)
        $result .= $characters[mt_rand(0, 61)];
?>

EDIT:
If you are concerned about security, really, do notuse rand()or mt_rand(), and verify that your random data device is actually a device generating randomdata, not a regular file or something predictable like /dev/zero. mt_rand()considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php

编辑:
如果您担心安全性,真的,请不要使用rand()mt_rand(),并验证您的随机数据设备实际上是生成随机数据的设备,而不是常规文件或可预测的/dev/zero. mt_rand()被认为有害:https:
//spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php

EDIT:If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():

编辑:如果您在 PHP 中有 OpenSSL 支持,您可以使用openssl_random_pseudo_bytes()

<?php
    $length = 5;
    $randomBytes = openssl_random_pseudo_bytes($length);
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $result = '';
    for ($i = 0; $i < $length; $i++)
        $result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>

回答by Kristoffer la Cour

I always use the same function for this, usually to generate passwords. It's easy to use and useful.

我总是为此使用相同的函数,通常用于生成密码。它易于使用且有用。

function randPass($length, $strength=8) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength >= 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength >= 2) {
        $vowels .= "AEUY";
    }
    if ($strength >= 4) {
        $consonants .= '23456789';
    }
    if ($strength >= 8) {
        $consonants .= '@#$%';
    }

    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

回答by Creeperstanson

It seems like str_shufflewould be a good use for this. Seed the shuffle with whichever characters you want.

似乎str_shuffle对此很有用。使用您想要的任何字符进行随机播放。

$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);

回答by edrian

$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
    //97 is ascii code for 'a' and 122 is ascii code for z
    $str .= chr(rand(97, 122));
}
return $str

回答by edrian

I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:

在我想到使用 PHP 之前,我也不知道该怎么做array。而且我很确定这是使用数组生成随机字符串或数字的最简单方法。编码:

function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
    $letters = str_split($abc);
    $str = "";
    for ($i=0; $i<=$len; $i++) {
        $str .= $letters[rand(0, count($letters)-1)];
    };
    return $str;
};

You can use this function like this

您可以像这样使用此功能

randstr(20)     // returns a random 20 letter string
                // Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"

回答by gronostaj

If it's fine that you'll get only letters A-F, then here's my solution:

如果你只得到字母 AF 没问题,那么这是我的解决方案:

str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);

I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex+ mt_randwill do the same job, but without unnecessary cryptographic work. str_padguarantees 5-character length of the output string (if the random number is less than 0x10000).

我相信使用散列函数对于生成随机十六进制数字序列这样简单的任务来说是一种矫枉过正。dechex+mt_rand会做同样的工作,但没有不必要的加密工作。str_pad保证输出字符串的 5 个字符长度(如果随机数小于 0x10000)。

Duplicate probability depends on mt_rand's reliability. Mersenne Twisteris known for high-quality randomness, so it should fit the task well.

重复概率取决于mt_rand的可靠性。Mersenne Twister以高质量的随机性而闻名,因此它应该很适合这项任务。