如何可能生成一个随机的,唯一的字符串使用数字和字母用于验证链接?就像你在一个网站上创建了一个账户,它会给你发一封带有链接的电子邮件,你必须点击那个链接才能验证你的账户

如何使用PHP生成其中一个?


当前回答

这个人被一杯水呛到……

$random= substr(str_shuffle(" 0123456789abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvwxyz *.-_"), 0,10);

简单。 这个随机字符串重复的可能性是0,000000000000000000000000000001^70

其他回答

以下是我使用的方法:

md5(time() . rand());    
// Creates something like 0c947c3b1047334f5bb8a3b7adc1d97b

PHP 7标准库提供了random_bytes($length)函数,该函数生成加密安全的伪随机字节。

例子:

$bytes = random_bytes(20);
var_dump(bin2hex($bytes));

上面的例子将输出类似于:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

更多信息:http://php.net/manual/en/function.random-bytes.php

PHP 5(过时)

我只是在寻找如何解决这个相同的问题,但我也希望我的函数创建一个令牌,可以用于密码检索以及。这意味着我需要限制令牌的猜测能力。因为uniqid是基于时间的,而根据php.net“返回值与microtime()相差不大”,uniqid不符合条件。PHP建议使用openssl_random_pseudo_bytes()来生成加密安全的令牌。

一个快速、简短、直截了当的答案是:

bin2hex(openssl_random_pseudo_bytes($bytes))

它将生成一个长度= $bytes * 2的字母数字字符的随机字符串。不幸的是,这只有一个字母[a-f][0-9],但它是有效的。


Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
    $range = $max - $min;
    if ($range < 1) return $min; // not so random...
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1; // length in bytes
    $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        $rnd = $rnd & $filter; // discard irrelevant bits
    } while ($rnd > $range);
    return $min + $rnd;
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    $max = strlen($codeAlphabet); // edited

    for ($i=0; $i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
    }

    return $token;
}

Crypto_rand_secure ($min, $max)作为rand()或mt_rand的替换。它使用openssl_random_pseudo_bytes来帮助创建一个介于$min和$max之间的随机数。

getToken($length)创建一个要在令牌中使用的字母表,然后创建一个长度为$length的字符串。

来源:http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php # 104322

投票最多的解决方案的面向对象版本

我根据Scott的回答创建了一个面向对象的解决方案:

<?php

namespace Utils;

/**
 * Class RandomStringGenerator
 * @package Utils
 *
 * Solution taken from here:
 * http://stackoverflow.com/a/13733588/1056679
 */
class RandomStringGenerator
{
    /** @var string */
    protected $alphabet;

    /** @var int */
    protected $alphabetLength;


    /**
     * @param string $alphabet
     */
    public function __construct($alphabet = '')
    {
        if ('' !== $alphabet) {
            $this->setAlphabet($alphabet);
        } else {
            $this->setAlphabet(
                  implode(range('a', 'z'))
                . implode(range('A', 'Z'))
                . implode(range(0, 9))
            );
        }
    }

    /**
     * @param string $alphabet
     */
    public function setAlphabet($alphabet)
    {
        $this->alphabet = $alphabet;
        $this->alphabetLength = strlen($alphabet);
    }

    /**
     * @param int $length
     * @return string
     */
    public function generate($length)
    {
        $token = '';

        for ($i = 0; $i < $length; $i++) {
            $randomKey = $this->getRandomInteger(0, $this->alphabetLength);
            $token .= $this->alphabet[$randomKey];
        }

        return $token;
    }

    /**
     * @param int $min
     * @param int $max
     * @return int
     */
    protected function getRandomInteger($min, $max)
    {
        $range = ($max - $min);

        if ($range < 0) {
            // Not so random...
            return $min;
        }

        $log = log($range, 2);

        // Length in bytes.
        $bytes = (int) ($log / 8) + 1;

        // Length in bits.
        $bits = (int) $log + 1;

        // Set all lower bits to 1.
        $filter = (int) (1 << $bits) - 1;

        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));

            // Discard irrelevant bits.
            $rnd = $rnd & $filter;

        } while ($rnd >= $range);

        return ($min + $rnd);
    }
}

使用

<?php

use Utils\RandomStringGenerator;

// Create new instance of generator class.
$generator = new RandomStringGenerator;

// Set token length.
$tokenLength = 32;

// Call method to generate random string.
$token = $generator->generate($tokenLength);

自定义的字母

如果需要,可以使用自定义字母。 只需要向构造函数或setter传递一个支持字符的字符串:

<?php

$customAlphabet = '0123456789ABCDEF';

// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);

// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);

下面是输出示例

SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa

我希望它能帮助到一些人。干杯!

我在这里提供了一些很好的研究数据,基于斯科特的答案提供的功能。因此,我为这个为期5天的自动化测试设置了一个数字海洋液滴,并将生成的唯一字符串存储在MySQL数据库中。

在这个测试期间,我使用了5个不同的长度(5、10、15、20、50),每个长度插入+/- 50万条记录。在我的测试中,在50万个重复中,只有长度5产生了+/-3K个重复,其余长度没有产生任何重复。所以我们可以说,如果我们使用Scott函数的长度为15或以上,那么我们就可以生成高度可靠的唯一字符串。以下是我的研究数据:

更新

我使用这些函数创建了一个简单的Heroku应用程序,它将令牌作为JSON响应返回。该应用程序可以在https://uniquestrings.herokuapp.com/api/token?length=15上访问

function codeGenerate() {
  $randCode  = (string)mt_rand(1000,9999);
  $randChar  = rand(65,90);
  $randInx   = rand(0,3);
  $randCode[$randInx] = chr($randChar);
  return $randCode;
}
echo codeGenerate();

输出

38I7
33V7
E836
736U