Home >Backend Development >PHP Tutorial >[PHP] Use openssl_random_pseudo_bytes and base64_encode functions to generate random strings_PHP tutorial

[PHP] Use openssl_random_pseudo_bytes and base64_encode functions to generate random strings_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 09:57:27972browse

[PHP] Use openssl_random_pseudo_bytes and base64_encode functions to generate random strings

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(&#39;openssl_random_pseudo_bytes&#39;)) {
            $bytes = openssl_random_pseudo_bytes($length * 2);

            if ($bytes === false)
                throw new RuntimeException(&#39;Unable to generate a random string&#39;);

            return substr(str_replace([&#39;/&#39;, &#39;+&#39;, &#39;=&#39;], &#39;&#39;, base64_encode($bytes)), 0, $length);
        }

        $pool = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;

        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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/981960.htmlTechArticle[PHP] Use openssl_random_pseudo_bytes and base64_encode functions to generate random strings. The openssl_random_pseudo_bytes function itself is used to generate the specified number. Random bytes, so when using...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn