[PHP] uses the openssl_random_pseudo _ bytes and base64_encode functions to generate a random string. the openssl_random_pseudo _ bytes function is used to generate a specified number of random bytes. Therefore, when using it to generate random strings, you also need to use the base64_encode function. As follows:
public static function getRandomString($length = 42) { /* * Use OpenSSL (if available) */ if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length * 2); if ($bytes === false) throw new RuntimeException('Unable to generate a random string'); return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length); } $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle(str_repeat($pool, 5)), 0, $length); }
After the base64_encode function is called, a replacement operation is performed on the result to remove unnecessary characters from the randomly generated string.
Of course, before using the openssl_random_pseudo _ bytes function, it is best to use function_exists to ensure that the function is available at runtime. If not, use Plan B:
substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
This function is highly versatile and can be modified as needed and called as a static method.