Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Thư viện tiêu chuẩn PHP 7 cung cấp chức năng

md5(uniqid($your_user_login, true))
4 tạo ra các byte giả ngẫu nhiên bảo mật bằng mã hóa.

Example:

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

Ví dụ trên sẽ xuất ra một cái gì đó tương tự như:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"

Thông tin thêm: http://php.net/manual/en/function.random-bytes.php

Php 5 (lỗi thời)

Tôi chỉ đang xem xét cách giải quyết vấn đề tương tự này, nhưng tôi cũng muốn chức năng của mình tạo ra một mã thông báo có thể được sử dụng để truy xuất mật khẩu. Điều này có nghĩa là tôi cần giới hạn khả năng của mã thông báo được đoán. Bởi vì

md5(uniqid($your_user_login, true))
5 dựa trên thời gian và theo php.net "giá trị trả về ít khác với microtime ()",
md5(uniqid($your_user_login, true))
5 không đáp ứng các tiêu chí. PHP khuyến nghị sử dụng
md5(uniqid($your_user_login, true))
7 thay vào đó để tạo mã thông báo bảo mật bằng mã hóa.

Một câu trả lời nhanh chóng, ngắn và đến điểm là:

bin2hex(openssl_random_pseudo_bytes($bytes))

sẽ tạo ra một chuỗi ngẫu nhiên các ký tự chữ và số có độ dài = $ byte * 2. Thật không may, điều này chỉ có bảng chữ cái là

md5(uniqid($your_user_login, true))
8, nhưng nó hoạt động.


Dưới đây là chức năng mạnh nhất mà tôi có thể làm cho điều đó đáp ứng các tiêu chí (đây là phiên bản được triển khai của câu trả lời của Erik).

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;
}

md5(uniqid($your_user_login, true))
9 hoạt động như một sự sụt giảm trong thay thế cho
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);
    }
}
0 hoặc
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);
    }
}
1. Nó sử dụng openSSL_random_pseudo_bytes để giúp tạo một số ngẫu nhiên giữa $ min và $ max.

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);
    }
}
2 tạo bảng chữ cái để sử dụng trong mã thông báo và sau đó tạo một chuỗi độ dài
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);
    }
}
3.

Nguồn: http://us1.php.net/manual/en/function.openssl-random-pseudo-byte.php#104322

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Gagarine

4.0322 Huy hiệu vàng29 Huy hiệu bạc39 Huy hiệu đồng2 gold badges29 silver badges39 bronze badges

Đã trả lời ngày 5 tháng 12 năm 2012 lúc 22:25Dec 5, 2012 at 22:25

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

ScottscottScott

11.8K4 Huy hiệu vàng27 Huy hiệu bạc48 Huy hiệu đồng4 gold badges27 silver badges48 bronze badges

31

Thông báo bảo mật: Giải pháp này không nên được sử dụng trong các tình huống mà chất lượng của tính ngẫu nhiên của bạn có thể ảnh hưởng đến bảo mật của một ứng dụng. Cụ thể,

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);
    }
}
0 và
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);
    }
}
5 không phải là bộ tạo số ngẫu nhiên bảo mật bằng mã hóa. Xem câu trả lời của Scott để biết thay thế an toàn.
: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular,
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);
    }
}
0 and
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);
    }
}
5 are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

Nếu bạn không cần nó hoàn toàn độc đáo theo thời gian:

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);
    }
}
6

Mặt khác (cho bạn đã xác định một đăng nhập duy nhất cho người dùng của bạn):

md5(uniqid($your_user_login, true))

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Đã trả lời ngày 4 tháng 12 năm 2009 lúc 10:55Dec 4, 2009 at 10:55

Loletechloletechloletech

3.6621 Huy hiệu vàng14 Huy hiệu bạc3 Huy hiệu đồng1 gold badge14 silver badges3 bronze badges

6

Phiên bản hướng đối tượng của giải pháp được bỏ phiếu nhiều nhất

Tôi đã tạo một giải pháp hướng đối tượng dựa trên câu trả lời của Scott:Scott's answer:

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);
    }
}

Cách sử dụng

generate($tokenLength);

Bảng chữ cái tùy chỉnh

Bạn có thể sử dụng bảng chữ cái tùy chỉnh nếu được yêu cầu. Chỉ cần chuyển một chuỗi với các ký tự được hỗ trợ cho hàm tạo hoặc setter:

setAlphabet($customAlphabet);

Đây là các mẫu đầu ra

SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa

Tôi hy vọng nó sẽ giúp ai đó. Chúc mừng!

Đã trả lời ngày 4 tháng 6 năm 2014 lúc 9:46Jun 4, 2014 at 9:46

Slava fomin iislava fomin IISlava Fomin II

25K27 Huy hiệu vàng117 Huy hiệu bạc194 Huy hiệu đồng27 gold badges117 silver badges194 bronze badges

5

Tôi ở đây với một số dữ liệu nghiên cứu tốt dựa trên các chức năng được cung cấp bởi câu trả lời của Scott. Vì vậy, tôi đã thiết lập một giọt đại dương kỹ thuật số chỉ cho thử nghiệm tự động dài 5 ngày này và lưu trữ các chuỗi độc đáo được tạo trong cơ sở dữ liệu MySQL.

Trong giai đoạn thử nghiệm này, tôi đã sử dụng 5 độ dài khác nhau (5, 10, 15, 20, 50) và +/- 0,5 triệu bản đã được chèn cho mỗi độ dài. Trong quá trình thử nghiệm của tôi, chỉ có độ dài 5 được tạo ra +/- 3K nhân đôi trong số 0,5 triệu và độ dài còn lại không tạo ra bất kỳ bản sao nào. Vì vậy, chúng ta có thể nói rằng nếu chúng ta sử dụng chiều dài từ 15 trở lên với các chức năng của Scott, thì chúng ta có thể tạo ra các chuỗi độc đáo đáng tin cậy cao. Dưới đây là bảng hiển thị dữ liệu nghiên cứu của tôi:

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Cập nhật

Tôi đã tạo một ứng dụng Heroku đơn giản bằng cách sử dụng các chức năng này trả về mã thông báo dưới dạng phản hồi JSON. Ứng dụng có thể được truy cập tại https://uniquestrings.herokuapp.com/api/token?length=15

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

HALFER

19.7K17 Huy hiệu vàng92 Huy hiệu bạc178 Huy hiệu đồng17 gold badges92 silver badges178 bronze badges

Đã trả lời ngày 5 tháng 6 năm 2017 lúc 9:14Jun 5, 2017 at 9:14

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

RehmatrehmatRehmat

4.4413 Huy hiệu vàng21 Huy hiệu bạc37 Huy hiệu đồng3 gold badges21 silver badges37 bronze badges

3

Bạn có thể sử dụng UUID (định danh độc đáo phổ biến), nó có thể được sử dụng cho bất kỳ mục đích nào, từ chuỗi xác thực người dùng đến ID giao dịch thanh toán.

UUID là một số 16 octet (128 bit). Ở dạng chính tắc, một UUID được biểu thị bằng 32 chữ số thập lục phân, được hiển thị thành năm nhóm được phân tách bằng dấu gạch nối, ở dạng 8-4-4-4-12 cho tổng số 36 ký tự (32 ký tự chữ và số và bốn dấu gạch nối).

function generate_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0C2f ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
    );

}

// Gọi Funtion

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
0

Một số đầu ra ví dụ sẽ giống như:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
1

Hy vọng nó sẽ giúp ai đó trong tương lai :)

Đã trả lời ngày 11 tháng 8 năm 2016 lúc 13:38Aug 11, 2016 at 13:38

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Nhà phát triểnDeveloper

3.7174 huy hiệu vàng36 Huy hiệu bạc46 Huy hiệu đồng4 gold badges36 silver badges46 bronze badges

1

Hàm này sẽ tạo một khóa ngẫu nhiên bằng cách sử dụng các số và chữ cái:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
2

Ví dụ đầu ra:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
3

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Đã trả lời ngày 24 tháng 9 năm 2012 lúc 18:16Sep 24, 2012 at 18:16

2

Tôi sử dụng một lớp này:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
4

trong đó độ dài là chiều dài của chuỗi mong muốn (chia hết cho 4, nếu không nó sẽ được làm tròn xuống số gần nhất chia cho 4)

Đã trả lời ngày 12 tháng 10 năm 2014 lúc 3:07Oct 12, 2014 at 3:07

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

DudeonrockdudeonrockDudeOnRock

3.5263 huy hiệu vàng27 Huy hiệu bạc57 Huy hiệu đồng3 gold badges27 silver badges57 bronze badges

2

Sử dụng mã bên dưới để tạo số ngẫu nhiên của 11 ký tự hoặc thay đổi số theo yêu cầu của bạn.

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
5

Hoặc chúng ta có thể sử dụng chức năng tùy chỉnh để tạo số ngẫu nhiên

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
6

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Sahil

1.33513 Huy hiệu bạc33 Huy hiệu đồng13 silver badges33 bronze badges

Đã trả lời ngày 5 tháng 12 năm 2016 lúc 12:54Dec 5, 2016 at 12:54

3

  1. Tạo một số ngẫu nhiên bằng cách sử dụng trình tạo số ngẫu nhiên yêu thích của bạn
  2. Nhân và chia nó để nhận một số khớp với số lượng ký tự trong bảng chữ cái mã của bạn
  3. Nhận mục tại chỉ mục đó trong bảng chữ cái mã của bạn.
  4. Lặp lại từ 1) cho đến khi bạn có độ dài bạn muốn

ví dụ: trong mã giả)

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
7

Đã trả lời ngày 4 tháng 12 năm 2009 lúc 10:52Dec 4, 2009 at 10:52

1

Đối với các chuỗi thực sự ngẫu nhiên, bạn có thể sử dụng

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
8

đầu ra:

string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
9

Vì vậy, ngay cả khi bạn cố gắng tạo chuỗi nhiều lần cùng một lúc, bạn sẽ nhận được đầu ra khác nhau.

Đã trả lời ngày 11 tháng 5 năm 2018 lúc 13:28May 11, 2018 at 13:28

Đây là một hàm đơn giản cho phép bạn tạo các chuỗi ngẫu nhiên chứa các chữ cái và số (chữ và số). Bạn cũng có thể giới hạn độ dài chuỗi. Các chuỗi ngẫu nhiên này có thể được sử dụng cho các mục đích khác nhau, bao gồm: mã giới thiệu, mã quảng cáo, mã phiếu giảm giá. Chức năng dựa vào các chức năng PHP sau: Base_Convert, SHA1, Uniqid, MT_Randbase_convert, sha1, uniqid, mt_rand

bin2hex(openssl_random_pseudo_bytes($bytes))
0

Đã trả lời ngày 23 tháng 7 năm 2018 lúc 11:44Jul 23, 2018 at 11:44

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Arpit J.Arpit J.Arpit J.

1.09112 Huy hiệu bạc19 Huy hiệu đồng12 silver badges19 bronze badges

Khi cố gắng tạo mật khẩu ngẫu nhiên, bạn đang cố gắng:

  • Đầu tiên tạo ra một tập hợp các byte ngẫu nhiên bảo mật bằng mã hóa

  • Thứ hai là biến những byte ngẫu nhiên đó thành một chuỗi có thể in được

Bây giờ, có nhiều cách để tạo các byte ngẫu nhiên trong PHP như:

bin2hex(openssl_random_pseudo_bytes($bytes))
1

Sau đó, bạn muốn biến các byte ngẫu nhiên này thành một chuỗi có thể in:

Bạn có thể sử dụng BIN2HEX:bin2hex :

bin2hex(openssl_random_pseudo_bytes($bytes))
2

hoặc base64_encode:base64_encode :

bin2hex(openssl_random_pseudo_bytes($bytes))
3

Tuy nhiên, lưu ý rằng bạn không kiểm soát độ dài của chuỗi nếu bạn sử dụng Base64. Bạn có thể sử dụng bin2hex để làm điều đó, sử dụng 32 byte sẽ biến thành chuỗi char 64. Nhưng nó sẽ chỉ hoạt động như vậy trong một chuỗi chẵn.32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.

Vì vậy, về cơ bản bạn có thể làm: :

bin2hex(openssl_random_pseudo_bytes($bytes))
4

Đã trả lời ngày 12 tháng 4 năm 2019 lúc 9:04Apr 12, 2019 at 9:04

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Dylan Kasdylan KasDylan KAS

3.9052 Huy hiệu vàng12 Huy hiệu bạc31 Huy hiệu đồng2 gold badges12 silver badges31 bronze badges

Đây là những gì tôi sử dụng:

bin2hex(openssl_random_pseudo_bytes($bytes))
5

Đã trả lời ngày 27 tháng 5 năm 2015 lúc 16:29May 27, 2015 at 16:29

1

Những người này nghẹn ngào trên một ly nước ...

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);
    }
}
7

Giản dị. Khả năng tích cực cho chuỗi ngẫu nhiên này lặp lại là 0,000000000000000000000000000001^70

Đã trả lời ngày 27 tháng 6 năm 2021 lúc 0:02Jun 27, 2021 at 0:02

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

2

Đây là trình tạo id độc đáo cuối cùng cho bạn. được thực hiện bởi tôi.

bin2hex(openssl_random_pseudo_bytes($bytes))
6

Bạn có thể lặp lại bất kỳ 'var' nào cho ID của bạn như bạn muốn. Nhưng $ mdun tốt hơn, bạn có thể thay thế MD5 thành SHA1 để có mã tốt hơn nhưng điều đó sẽ rất dài mà bạn không cần.

Cảm ơn bạn.

Đã trả lời ngày 17 tháng 7 năm 2013 lúc 23:08Jul 17, 2013 at 23:08

2

Tôi thích sử dụng các khóa băm khi giao dịch các liên kết xác minh. Tôi khuyên bạn nên sử dụng microtime và băm rằng sử dụng MD5 vì không có lý do tại sao các khóa phải giống nhau vì nó băm dựa trên microtime.

  1. 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);
        }
    }
    
    8
  2. 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);
        }
    }
    
    9

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

René Vogt

42.3K14 Huy hiệu vàng76 Huy hiệu bạc95 Huy hiệu Đồng14 gold badges76 silver badges95 bronze badges

Đã trả lời ngày 7 tháng 3 năm 2016 lúc 4:58Mar 7, 2016 at 4:58

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

bin2hex(openssl_random_pseudo_bytes($bytes))
7

Đã trả lời ngày 8 tháng 1 năm 2014 lúc 12:20Jan 8, 2014 at 12:20

NidhinnidhinNidhin

1.80822 Huy hiệu bạc22 Huy hiệu đồng22 silver badges22 bronze badges

Trình tạo băm 'một dòng đơn giản' như

generate($tokenLength);
0 (1Byte = 2Chars)

bin2hex(openssl_random_pseudo_bytes($bytes))
8

Đã trả lời ngày 26 tháng 7 năm 2021 lúc 6:59Jul 26, 2021 at 6:59

Sau khi đọc các ví dụ trước, tôi đã đưa ra điều này:

bin2hex(openssl_random_pseudo_bytes($bytes))
9

Tôi sao chép gấp 10 lần mảng [0-9, a-z] và xáo trộn các phần tử, sau khi tôi nhận được điểm bắt đầu ngẫu nhiên để con () sáng tạo hơn :) Bạn có thể thêm [A-Z] và các yếu tố khác vào mảng, sao chép ít nhiều, sáng tạo hơn tôi

Đã trả lời ngày 25 tháng 2 năm 2015 lúc 16:09Feb 25, 2015 at 16:09

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;
}
0

Chức năng trên sẽ tạo cho bạn một chuỗi ngẫu nhiên có độ dài 11 ký tự.

Đã trả lời ngày 20 tháng 5 năm 2017 lúc 11:21May 20, 2017 at 11:21

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Nếu bạn muốn tạo một chuỗi duy nhất trong PHP, hãy thử theo sau.

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;
}
1

Trong này,

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);
    }
}
5 - Nó sẽ tạo ra chuỗi duy nhất. Hàm này trả về định danh duy nhất dựa trên dấu thời gian dưới dạng chuỗi.

generate($tokenLength);
2 - Tạo số ngẫu nhiên.

generate($tokenLength);
3 - Nó sẽ tạo chuỗi băm.

Đã trả lời ngày 6 tháng 12 năm 2018 lúc 8:24Dec 6, 2018 at 8:24

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Akshaypjoshiakshaypjoshiakshaypjoshi

1.2161 Huy hiệu vàng14 Huy hiệu bạc23 Huy hiệu đồng1 gold badge14 silver badges23 bronze badges

Tôi luôn sử dụng chức năng này để tạo chuỗi chữ và số ngẫu nhiên tùy chỉnh ... hy vọng điều này sẽ giúp.

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;
}
2

Nó tạo ví dụ:

Nếu bạn muốn so sánh với một chuỗi khác để chắc chắn rằng đó là một chuỗi duy nhất, bạn có thể sử dụng thủ thuật này ...

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;
}
3

Nó tạo ra hai chuỗi duy nhất:

qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi

Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF

Hy vọng đây là những gì bạn đang tìm kiếm...

Đã trả lời ngày 9 tháng 3 năm 2019 lúc 18:58Mar 9, 2019 at 18:58

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

AlessandroalessandroAlessandro

8429 Huy hiệu bạc23 Huy hiệu Đồng9 silver badges23 bronze badges

Một giải pháp đơn giản là chuyển đổi cơ sở 64 thành chữ và số bằng cách loại bỏ các ký tự không phải là ký sinh viên.

Cái này sử dụng Random_Bytes () cho kết quả bảo mật bằng mã hóa.

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;
}
4

EDIT: Tôi chỉ xem lại điều này bởi vì tôi cần một cái gì đó linh hoạt hơn một chút. Dưới đây là một giải pháp hoạt động tốt hơn một chút so với trên và cung cấp tùy chọn để chỉ định bất kỳ tập hợp con nào của bộ ký tự ASCII:

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;
}
5

Đã trả lời ngày 8 tháng 2 năm 2020 lúc 23:50Feb 8, 2020 at 23:50

Jon Hulkajon HulkaJon Hulka

1.23910 huy hiệu bạc15 huy hiệu đồng10 silver badges15 bronze badges

Người ta có thể sử dụng mã này. Tôi đã thử nghiệm với 35.000,00 ID không có bản sao.

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;
}
6

Bạn có thể tự do sửa đổi nó là nhu cầu của bạn. Và nếu bạn có bất kỳ đề xuất nào, vui lòng bình luận. Bạn nên kiểm tra mọi ID trong cơ sở dữ liệu của mình trước khi sử dụng ID này bằng cách thực hiện rằng bạn có ID duy nhất 100% trong cơ sở dữ liệu của mình.

Đã trả lời ngày 10 tháng 11 năm 2021 lúc 8:59Nov 10, 2021 at 8:59

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Somen Dassomen DasSomen Das

1511 Huy hiệu bạc6 Huy hiệu đồng1 silver badge6 bronze badges

1

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;
}
7

Đầu ra

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;
}
8

Đã trả lời ngày 12 tháng 8 lúc 10:14Aug 12 at 10:14

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Ram Pukarram PukarRam Pukar

1.50113 huy hiệu bạc16 Huy hiệu đồng13 silver badges16 bronze badges

Scott, vâng, bạn rất viết và giải pháp tốt! Cảm ơn.

Tôi cũng được yêu cầu tạo mã thông báo API duy nhất cho mỗi người dùng. Sau đây là cách tiếp cận của tôi, tôi đã sử dụng thông tin người dùng (userID và tên người dùng):

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;
}
9

Xin hãy xem và cho tôi biết nếu bất kỳ cải tiến tôi có thể làm. Cảm ơn

Đã trả lời ngày 25 tháng 3 năm 2014 lúc 15:59Mar 25, 2014 at 15:59

Đây là những gì tôi đang sử dụng trên một trong các dự án của mình, nó hoạt động rất tốt và nó tạo ra một mã thông báo ngẫu nhiên độc đáo:UNIQUE RANDOM TOKEN:

md5(uniqid($your_user_login, true))
0

Xin lưu ý rằng tôi đã nhân dấu thời gian với ba lần để tạo ra sự nhầm lẫn cho bất cứ ai người dùng có thể tự hỏi làm thế nào mã thông báo này được tạo ra;)

Tôi hy vọng nó sẽ giúp :)

Đã trả lời ngày 1 tháng 8 năm 2015 lúc 9:41Aug 1, 2015 at 9:41

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Fery Kaszonifery KaszoniFery Kaszoni

3.9101 Huy hiệu vàng18 Huy hiệu bạc11 Huy hiệu đồng1 gold badge18 silver badges11 bronze badges

2

Tôi nghĩ rằng đây là phương pháp tốt nhất để sử dụng.

md5(uniqid($your_user_login, true))
1

Đã trả lời ngày 18 tháng 4 năm 2017 lúc 6:14Apr 18, 2017 at 6:14

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Đây là một điều thú vị

md5(uniqid($your_user_login, true))
2

Bị đánh cắp từ Laravel ở đây

Đã trả lời ngày 16 tháng 5 năm 2021 lúc 17:08May 16, 2021 at 17:08

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

Tôi tin rằng vấn đề với tất cả các ý tưởng hiện có là chúng có lẽ là duy nhất, nhưng không chắc chắn là duy nhất (như được chỉ ra trong câu trả lời của Dariusz Walczak cho Loletech). Tôi có một giải pháp thực sự là duy nhất. Nó yêu cầu tập lệnh của bạn có một số loại bộ nhớ. Đối với tôi đây là cơ sở dữ liệu SQL. Bạn cũng có thể chỉ cần viết vào một tập tin ở đâu đó. Có hai triển khai:

Phương pháp đầu tiên: Có hai trường thay vì 1 cung cấp tính độc đáo. Trường đầu tiên là số ID không phải là ngẫu nhiên nhưng là duy nhất (ID đầu tiên là 1, thứ hai 2 ...). Nếu bạn đang sử dụng SQL, chỉ cần xác định trường ID với thuộc tính Auto_increment. Trường thứ hai không phải là duy nhất nhưng là ngẫu nhiên. Điều này có thể được tạo ra với bất kỳ kỹ thuật nào khác mà mọi người đã đề cập. Ý tưởng của Scott là tốt, nhưng MD5 thuận tiện và có thể đủ tốt cho hầu hết các mục đích:

md5(uniqid($your_user_login, true))
3

Phương pháp thứ hai: Về cơ bản cùng một ý tưởng, nhưng ban đầu chọn số lượng chuỗi tối đa sẽ được tạo ra. Đây chỉ có thể là một con số thực sự lớn như một nghìn tỷ. Sau đó làm điều tương tự, tạo ID, nhưng không có pad để tất cả các ID là cùng một số chữ số. Sau đó, chỉ cần nối ID với chuỗi ngẫu nhiên. Nó sẽ đủ ngẫu nhiên cho hầu hết các mục đích, nhưng phần ID sẽ đảm bảo rằng nó cũng là duy nhất.

Đã trả lời ngày 28 tháng 11 năm 2014 lúc 7:13Nov 28, 2014 at 7:13

Hướng dẫn how to generate random unique id in php? - làm thế nào để tạo id duy nhất ngẫu nhiên trong php?

BytesizedBytesizedbytesized

1.49012 Huy hiệu bạc22 Huy hiệu đồng12 silver badges22 bronze badges

Làm thế nào để bạn tạo ra các chuỗi ngẫu nhiên độc đáo?

Phương tiện độc đáo: Chuỗi được tạo không thể là một trong trường đã tạo ra trường DataBase BeetableUser được tạo ra. Vì vậy, nên có hai bước: 1) tạo ra một chuỗi 5 ký tự ngẫu nhiên, chỉ chữ cái chữ thường; 2) Kiểm tra xem chuỗi có trong cơ sở dữ liệu không, nếu có, tái tạo một chuỗi ngẫu nhiên cho đến khi nó không có trong cơ sở dữ liệu.generate a random 5 character string, lower case letter only; 2) check if the string is in database, if yes, regenerate a random string until it is not in the database.

Làm cách nào để tạo số 4 chữ số ngẫu nhiên trong PHP?

Rand ()*(9999-1000) +1000: Điều này sẽ chủ yếu nhân 9999 với hàm RAND để tạo số 4 chữ số.Int (rand ()*(9999-1000) +1000: Điều này sẽ lấy số nguyên gần nhất của số ngẫu nhiên và chỉ tạo 4 chữ số trên các số ngẫu nhiên.: This will mainly multiply 9999 with the RAND function to generate 4-digit numbers. INT(RAND()*(9999-1000)+1000: This will take the closest integer of the random number and generate only the 4-digit on random numbers.

Làm cách nào để tạo một ký tự ngẫu nhiên trong PHP?

Sử dụng hàm str_shuffle (): hàm str_shuffle () là hàm sẵn có trong PHP và được sử dụng để xáo trộn ngẫu nhiên tất cả các ký tự của chuỗi được truyền đến hàm dưới dạng tham số.Khi một số được thông qua, nó coi số đó là chuỗi và xáo trộn nó.: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it.

Uniqid làm gì trong PHP?

Hàm uniqid () tạo ra một id duy nhất dựa trên microtime (thời gian hiện tại tính bằng micro giây).Lưu ý: ID được tạo từ hàm này không đảm bảo tính duy nhất của giá trị trả về!Để tạo ra một cực kỳ khó dự đoán ID, hãy sử dụng hàm md5 ().generates a unique ID based on the microtime (the current time in microseconds). Note: The generated ID from this function does not guarantee uniqueness of the return value! To generate an extremely difficult to predict ID, use the md5() function.