You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
1003 B
PHP
32 lines
1003 B
PHP
<?php
|
|
|
|
/*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
*/
|
|
|
|
class RandomString {
|
|
|
|
/**
|
|
* Generate a random string, using a cryptographically secure
|
|
* pseudorandom number generator (random_int)
|
|
*
|
|
* From https://stackoverflow.com/a/31107425
|
|
*
|
|
* @param int $length How many characters do we want?
|
|
* @param string $keyspace A string of all possible characters
|
|
* to select from
|
|
* @return string
|
|
*/
|
|
public static function generate(int $length, string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): string {
|
|
$pieces = [];
|
|
$max = mb_strlen($keyspace, '8bit') - 1;
|
|
for ($i = 0; $i < $length; ++$i) {
|
|
$pieces [] = $keyspace[random_int(0, $max)];
|
|
}
|
|
return implode('', $pieces);
|
|
}
|
|
|
|
}
|