The openssl_random_pseudo_bytes function itself is used to generate a specified number of random bytes, so when using it to generate a random string, you also need to use the function base64_encode. As shown below:
<code class="language-php hljs ">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); }</code>
After calling the base64_encode function, a replacement operation is performed on the result in order 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 available, use Plan B:
<code class="language-php hljs ">substr(str_shuffle(str_repeat($pool, 5)), 0, $length);</code>
This function is very versatile and can be modified appropriately according to business needs and then called as a static method.