Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Để trả lời câu hỏi này cụ thể, hai vấn đề:

  1. $a = random_str(32);
    $b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
    $c = random_str();
    
    3 không nằm trong phạm vi khi bạn lặp lại nó.
  2. Các nhân vật không được nối với nhau trong vòng lặp.

Đây là một đoạn mã với các hiệu chỉnh:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Xuất chuỗi ngẫu nhiên với cuộc gọi bên dưới:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Xin lưu ý rằng điều này tạo ra các chuỗi ngẫu nhiên có thể dự đoán được. Nếu bạn muốn tạo mã thông báo an toàn, hãy xem câu trả lời này.

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Steadweb

13.9k3 Huy hiệu vàng29 Huy hiệu bạc41 Huy hiệu đồng3 gold badges29 silver badges41 bronze badges

Đã trả lời ngày 4 tháng 12 năm 2010 lúc 22:57Dec 4, 2010 at 22:57

Stephen Watkinsstephen WatkinsStephen Watkins

24.5K14 Huy hiệu vàng65 Huy hiệu bạc98 Huy hiệu đồng14 gold badges65 silver badges98 bronze badges

16

Lưu ý:

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
4 sử dụng nội bộ
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
5, không phù hợp cho mục đích mật mã (ví dụ: tạo mật khẩu ngẫu nhiên). Bạn muốn một trình tạo số ngẫu nhiên an toàn thay thế. Nó cũng không cho phép các ký tự lặp lại.

Một cách nữa.

Đã cập nhật (bây giờ điều này tạo ra bất kỳ độ dài nào của chuỗi): (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)

Đó là nó. :)

Đã trả lời ngày 3 tháng 11 năm 2012 lúc 20:04Nov 3, 2012 at 20:04

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

A. Cheshirova. CheshirovA. Cheshirov

4.6561 Huy hiệu vàng13 Huy hiệu bạc13 Huy hiệu đồng1 gold badge13 silver badges13 bronze badges

20

Có rất nhiều câu trả lời cho câu hỏi này, nhưng không ai trong số họ tận dụng một trình tạo số giả ngẫu nhiên bảo mật bằng mã hóa (CSPRNG).

Câu trả lời đơn giản, an toàn và đúng đắn là sử dụng RandomLib và không phát minh lại bánh xe.

Đối với những người bạn khăng khăng phát minh ra giải pháp của riêng bạn, Php 7.0.0 sẽ cung cấp

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
6 cho mục đích này; Nếu bạn vẫn còn trên Php 5.x, chúng tôi đã viết một polyfill Php 5 cho
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
6 để bạn có thể sử dụng API mới ngay cả trước khi bạn nâng cấp lên Php 7.

Tạo một cách an toàn các số nguyên ngẫu nhiên trong PHP không phải là một nhiệm vụ tầm thường. Bạn nên luôn luôn kiểm tra với các chuyên gia về mật mã Stackexchange thường trú của bạn trước khi bạn triển khai một thuật toán trồng tại nhà trong sản xuất.

Với một bộ tạo số nguyên an toàn tại chỗ, tạo ra một chuỗi ngẫu nhiên với CSPRNG là một cuộc đi bộ trong công viên.

Tạo một chuỗi ngẫu nhiên, an toàn

/**
 * 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();

Bản demo: https://3v4l.org/imjgf (bỏ qua các lỗi Php 5; nó cần Random_compat): https://3v4l.org/IMJGF (Ignore the PHP 5 failures; it needs random_compat)

Đã trả lời ngày 29 tháng 6 năm 2015 lúc 3:41Jun 29, 2015 at 3:41

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Scott Arciszewskiscott ArciszewskiScott Arciszewski

32.7K16 Huy hiệu vàng87 Huy hiệu bạc204 Huy hiệu đồng16 gold badges87 silver badges204 bronze badges

15

Điều này tạo ra một chuỗi thập lục phân dài 20 ký tự:

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars

Trong 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

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Đã trả lời ngày 4 tháng 9 năm 2014 lúc 18:25Sep 4, 2014 at 18:25

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

8

@TasManiski: Câu trả lời của bạn đã làm việc cho tôi. Tôi đã có cùng một vấn đề, và tôi sẽ đề nghị nó cho những người đang tìm kiếm cùng một câu trả lời. Đây là từ @tasmaniski:


Đây là video YouTube chỉ cho chúng tôi cách tạo một số ngẫu nhiên

Đã trả lời ngày 10 tháng 2 năm 2013 lúc 8:24Feb 10, 2013 at 8:24

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

HumphreyhumphreyHumphrey

2.5233 huy hiệu vàng27 Huy hiệu bạc38 Huy hiệu đồng3 gold badges27 silver badges38 bronze badges

6

Tùy thuộc vào ứng dụng của bạn (tôi muốn tạo mật khẩu), bạn có thể sử dụng

$string = base64_encode(openssl_random_pseudo_bytes(30));

Là base64, chúng có thể chứa

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
8 hoặc
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
9 cũng như các ký tự được yêu cầu. Bạn có thể tạo một chuỗi dài hơn, sau đó lọc và cắt nó để loại bỏ chúng.

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
0 dường như là cách được khuyến nghị để tạo ra một số ngẫu nhiên thích hợp trong PHP. Tại sao
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
1 không sử dụng
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
2 tôi không biết.

Đã trả lời ngày 6 tháng 2 năm 2013 lúc 17:40Feb 6, 2013 at 17:40

rjmunrorjmunrorjmunro

26.4K20 Huy hiệu vàng108 Huy hiệu bạc132 Huy hiệu Đồng20 gold badges108 silver badges132 bronze badges

6

Php 7+ tạo ra các byte ngẫu nhiên bảo mật bằng mã hóa bằng cách sử dụng chức năng Random_Bytes. Generate cryptographically secure random bytes using random_bytes function.

$bytes = random_bytes(16);
echo bin2hex($bytes);

Đầu ra có thể

da821217e61e33ed4b2dd96f8439056c

Php 5.3+ tạo các byte giả ngẫu nhiên bằng cách sử dụng hàm openSSL_Random_pseudo_bytes. Generate pseudo-random bytes using openssl_random_pseudo_bytes function.

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
0

Đầu ra có thể

e2d1254506fbb6cd842cd640333214ad

Php 5.3+ tạo các byte giả ngẫu nhiên bằng cách sử dụng hàm openSSL_Random_pseudo_bytes.best use case could be

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
1

Đầu ra có thể

ba8cc342bdf91143

Php 5.3+ tạo các byte giả ngẫu nhiên bằng cách sử dụng hàm openSSL_Random_pseudo_bytes.Jan 25, 2020 at 3:12

Trường hợp sử dụng tốt nhất có thể làMadan Sapkota

Đã trả lời ngày 25 tháng 1 năm 2020 lúc 3:1211 gold badges112 silver badges115 bronze badges

7

Madan Sapkotamadan Sapkota

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
2

23.8K11 Huy hiệu vàng112 Huy hiệu bạc115 Huy hiệu đồng

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
3

Dưới đây là một lớp lót đơn giản tạo ra một chuỗi ngẫu nhiên thực sự mà không có bất kỳ vòng lặp cấp độ tập lệnh hoặc sử dụng thư viện OpenSSL.

Để phá vỡ nó để các tham số rõ ràng

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Phương thức này hoạt động bằng cách lặp lại ngẫu nhiên danh sách ký tự, sau đó xáo trộn chuỗi kết hợp và trả về số lượng ký tự được chỉ định.Apr 19, 2014 at 21:18

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Bạn có thể ngẫu nhiên hóa điều này, bằng cách chọn ngẫu nhiên độ dài của chuỗi được trả về, thay thế

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
3 bằng
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
4 (cho một chuỗi ngẫu nhiên giữa 8 đến 15 ký tự).Kraang Prime

Đã trả lời ngày 19 tháng 4 năm 2014 lúc 21:188 gold badges56 silver badges121 bronze badges

10

Kraang Primekraang Prime

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
4

9.6118 Huy hiệu vàng56 Huy hiệu bạc121 Huy hiệu Đồng

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Một cách tốt hơn để thực hiện chức năng này là:Sep 24, 2012 at 18:08

1

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
5

Tada!

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
5 là ngẫu nhiên hơn theo điều này và điều này trong PHP & NBSP; 7. Hàm
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
1 là bí danh của
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
5.Dec 26, 2012 at 16:32

Đã trả lời ngày 24 tháng 9 năm 2012 lúc 18:08Davor

Đã trả lời ngày 26 tháng 12 năm 2012 lúc 16:3216 silver badges32 bronze badges

8

Davordavor

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
6

1.38716 huy hiệu bạc32 huy hiệu đồng

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
7

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
3 trong phạm vi hàm không giống với phạm vi mà bạn gọi nó. Bạn phải gán giá trị trả về cho một biến.

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
8

Đã trả lời ngày 4 tháng 12 năm 2010 lúc 22:59Dec 4, 2010 at 22:59

BoltclockboltclockBoltClock

676K155 Huy hiệu vàng1362 Huy hiệu bạc1335 Huy hiệu Đồng155 gold badges1362 silver badges1335 bronze badges

Đầu tiên, bạn xác định bảng chữ cái bạn muốn sử dụng:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
9

Sau đó, sử dụng

$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
1 để tạo dữ liệu ngẫu nhiên thích hợp:

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
0

Cuối cùng, bạn sử dụng dữ liệu ngẫu nhiên này để tạo mật khẩu. Bởi vì mỗi ký tự trong

$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
2 có thể là
$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
3 cho đến
$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
4, mã sử dụng phần còn lại sau khi phân chia giá trị thứ tự của nó với
$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
5 để đảm bảo chỉ các ký tự từ bảng chữ cái được chọn (lưu ý rằng việc thực hiện sự ngẫu nhiên):

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
1

Ngoài ra, và nói chung tốt hơn, là sử dụng RandomLib và SecurityLib:

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
2

2

Tôi đã thử nghiệm hiệu suất của hầu hết các chức năng phổ biến ở đó, thời gian cần thiết để tạo 1'000'000 chuỗi 32 ký hiệu trên hộp của tôi là:

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
3

Xin lưu ý rằng nó không quan trọng là bao lâu nhưng nó chậm hơn và cái nào nhanh hơn để bạn có thể chọn theo yêu cầu của bạn bao gồm cả khả năng sẵn sàng mật mã, v.v.

Subr () xung quanh MD5 đã được thêm vào vì độ chính xác nếu bạn cần chuỗi ngắn hơn 32 ký hiệu.

Vì lợi ích của câu trả lời: Chuỗi không được nối nhưng bị ghi đè và kết quả của chức năng không được lưu trữ.

Đã trả lời ngày 24 tháng 10 năm 2017 lúc 12:09Oct 24, 2017 at 12:09

PutnikputnikPutnik

5,0085 Huy hiệu vàng35 Huy hiệu bạc54 Huy hiệu Đồng5 gold badges35 silver badges54 bronze badges

1

Đây là giải pháp một dòng đơn giản của tôi để tạo mật khẩu ngẫu nhiên thân thiện sử dụng, không bao gồm các ký tự trông giống như "1" và "l", "o" và "0", v.v. ... Đây là 5 ký tự nhưng bạn có thể dễ dàng Tất nhiên thay đổi nó:

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
4

Đã trả lời ngày 4 tháng 10 năm 2019 lúc 14:03Oct 4, 2019 at 14:03

RathusrathusrAthus

7927 Huy hiệu bạc14 Huy hiệu đồng7 silver badges14 bronze badges

7

Phương pháp ngắn ..

Dưới đây là một số phương pháp ngắn nhất để tạo chuỗi ngẫu nhiên

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
5

Đã trả lời ngày 7 tháng 2 năm 2017 lúc 6:12Feb 7, 2017 at 6:12

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Punit Gajjarpunit GajjarPunit Gajjar

4.6217 Huy hiệu vàng32 Huy hiệu bạc64 Huy hiệu đồng7 gold badges32 silver badges64 bronze badges

Một cách rất nhanh là làm một cái gì đó như:

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
6

Điều này sẽ tạo ra một chuỗi ngẫu nhiên với chiều dài 10 ký tự. Tất nhiên, một số người có thể nói rằng nó nặng hơn một chút về phía tính toán, nhưng các bộ xử lý ngày nay được tối ưu hóa để chạy thuật toán MD5 hoặc SHA256 rất nhanh. Và tất nhiên, nếu hàm

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
5 trả về cùng một giá trị, kết quả sẽ giống nhau, có cơ hội 1 /32767 giống nhau. Nếu bảo mật là vấn đề, thì chỉ cần thay đổi
$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
5 thành
$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
8

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

BASSMHL

7.5539 Huy hiệu vàng48 Huy hiệu bạc62 Huy hiệu Đồng9 gold badges48 silver badges62 bronze badges

Đã trả lời ngày 24 tháng 10 năm 2013 lúc 16:04Oct 24, 2013 at 16:04

AkatoshakatoshAkatosh

4289 Huy hiệu bạc17 Huy hiệu đồng9 silver badges17 bronze badges

0

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
7

Giá trị mặc định [5]: WVPJZ

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
8

Giá trị [30]: CAIGGTF1LDPFWOVWJYKNKXXV6SC4Q2

Đã trả lời ngày 3 tháng 1 lúc 17:13Jan 3 at 17:13

Ông Coderxmr. CoderxMr. Coderx

4616 Huy hiệu bạc4 Huy hiệu đồng6 silver badges4 bronze badges

Chức năng của người trợ giúp từ khung Laravel 5

function generateRandomString($length = 10) {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}

echo  generateRandomString();  // OR: generateRandomString(24)
9

Đã trả lời ngày 17 tháng 2 năm 2015 lúc 19:03Feb 17, 2015 at 19:03

artnikproartnikproartnikpro

5.1354 Huy hiệu vàng35 Huy hiệu bạc38 Huy hiệu đồng4 gold badges35 silver badges38 bronze badges

1

/**
 * 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);
}
0

Đã trả lời ngày 13 tháng 11 năm 2012 lúc 14:45Nov 13, 2012 at 14:45

1

Cái này được lấy từ các nguồn quản trị viên:

/**
 * 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);
}
1

Quản trị viên, Công cụ quản lý cơ sở dữ liệu được viết bằng PHP.

Đã trả lời ngày 2 tháng 8 năm 2016 lúc 3:15Aug 2, 2016 at 3:15

UserLonduserLonduserlond

3,4942 Huy hiệu vàng32 Huy hiệu bạc 50 Huy hiệu Đồng2 gold badges32 silver badges50 bronze badges

Từ khung Yii2

/**
 * 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);
}
2

SXN

1571 Huy hiệu bạc7 Huy hiệu đồng1 silver badge7 bronze badges

Đã trả lời ngày 7 tháng 10 năm 2020 lúc 9:45Oct 7, 2020 at 9:45

SxnsxnSXN

891 Huy hiệu bạc3 Huy hiệu đồng1 silver badge3 bronze badges

2

/**
 * 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);
}
3

Nguồn từ http://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-9-php/

mike_t

2.3822 Huy hiệu vàng19 Huy hiệu bạc37 Huy hiệu đồng2 gold badges19 silver badges37 bronze badges

Đã trả lời ngày 23 tháng 12 năm 2017 lúc 10:57Dec 23, 2017 at 10:57

sxnsxnsxn

1571 Huy hiệu bạc7 Huy hiệu đồng1 silver badge7 bronze badges

Đã trả lời ngày 7 tháng 10 năm 2020 lúc 9:45

/**
 * 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);
}
4

Sxnsxn

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

891 Huy hiệu bạc3 Huy hiệu đồngAug 1, 2014 at 14:20

Nguồn từ http://www.xeweb.net/2011/02/11/generate-a-random-string-a-z-0-9-9-php/kasimir

2.3822 Huy hiệu vàng19 Huy hiệu bạc37 Huy hiệu đồng1 gold badge20 silver badges24 bronze badges

3

Đã trả lời ngày 23 tháng 12 năm 2017 lúc 10:57

sxnsxn

/**
 * 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);
}
5

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Một lớp lót khác, tạo ra một chuỗi ngẫu nhiên gồm 10 ký tự với các chữ cái và số. Nó sẽ tạo một mảng với

$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
9 (điều chỉnh tham số thứ hai để đặt kích thước), các vòng lặp qua mảng này và gán một ký tự ASCII ngẫu nhiên (phạm vi 0-9 hoặc A-Z), sau đó tạo ra mảng để có một chuỗi.May 19, 2015 at 20:47

2

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

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Lưu ý: Điều này chỉ hoạt động trong Php 5.3 trở lênJan 20, 2017 at 16:35

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

Đã trả lời ngày 1 tháng 8 năm 2014 lúc 14:20Anjith K P

Kasimirkasimir26 silver badges35 bronze badges

1.4781 Huy hiệu vàng20 Huy hiệu bạc24 Huy hiệu đồng

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

Lót.

Nó là nhanh chóng cho các chuỗi lớn với một số độc đáo.

Đã trả lời ngày 19 tháng 5 năm 2015 lúc 20:47Apr 9, 2013 at 23:16

Đã trả lời ngày 20 tháng 1 năm 2017 lúc 16:35sherpa

Anjith k panjith k p1 silver badge2 bronze badges

4

2.15826 huy hiệu bạc35 huy hiệu đồng

Để khắc phục điều này, thay đổi:

/**
 * 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);
}
8

to:

/**
 * 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);
}
9

Bằng cách này, chỉ có các ký tự kèm theo được sử dụng và ký tự sẽ không bao giờ là một phần của chuỗi ngẫu nhiên được tạo ra.

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

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

BMCSWEEBMCSWEEbmcswee

1072 Huy hiệu bạc6 Huy hiệu đồng2 silver badges6 bronze badges

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
0

Và sử dụng:

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
1

Đã trả lời ngày 8 tháng 3 năm 2021 lúc 10:36Mar 8, 2021 at 10:36

Hướng dẫn how to generate random characters in php? - làm thế nào để tạo các ký tự ngẫu nhiên trong php?

MRMPMRMPMRMP

1831 Huy hiệu bạc5 Huy hiệu đồng1 silver badge5 bronze badges

Tôi thích nhận xét cuối cùng đã sử dụng openSSL_random_pseudo_bytes, nhưng đó không phải là một giải pháp cho tôi vì tôi vẫn phải xóa các ký tự mà tôi không muốn và tôi không thể có được một chuỗi độ dài được thiết lập. Đây là giải pháp của tôi ...

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
2

Đã trả lời ngày 10 tháng 2 năm 2013 lúc 21:02Feb 10, 2013 at 21:02

Làm thế nào để tôi chọn ngẫu nhiên trong PHP?

Hàm Rand () tạo ra một số nguyên ngẫu nhiên.Mẹo ví dụ: Nếu bạn muốn một số nguyên ngẫu nhiên trong khoảng từ 10 đến 100 (bao gồm), hãy sử dụng RAND (10.100).Mẹo: Kể từ Php 7.1, hàm rand () là bí danh của hàm mt_rand ().. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

Làm thế nào tôi có thể tạo 5 số ngẫu nhiên trong PHP?

Các hàm rand () hoặc mt_rand () có thể được sử dụng để tạo số ngẫu nhiên 5 chữ số trong PHP. can be used to Generate 5 Digit Random Number in PHP.

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

Có nhiều cách để tạo chuỗi chữ và số ngẫu nhiên, độc đáo trong PHP được đưa ra dưới đây: sử dụng hàm str_shuffle (): hàm str_shuffle ()cho chức năng như một tham số.Using str_shuffle() Function: 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.

Hàm MT_RAND trong PHP là gì?

Hàm mt_rand () tạo ra một số nguyên ngẫu nhiên bằng thuật toán twister mersenne.Mẹo ví dụ: Nếu bạn muốn một số nguyên ngẫu nhiên trong khoảng từ 10 đến 100 (bao gồm), hãy sử dụng MT_RAND (10.100).generates a random integer using the Mersenne Twister algorithm. Example tip: If you want a random integer between 10 and 100 (inclusive), use mt_rand (10,100).