Rumah >pembangunan bahagian belakang >tutorial php >[PHP]利用openssl_random_pseudo_bytes跟base64_encode函数来生成随机字符串

[PHP]利用openssl_random_pseudo_bytes跟base64_encode函数来生成随机字符串

WBOY
WBOYasal
2016-06-13 12:17:38992semak imbas

[PHP]利用openssl_random_pseudo_bytes和base64_encode函数来生成随机字符串

openssl_random_pseudo_bytes函数本身是用来生成指定个数的随机字节,因此在使用它来生成随机字符串时,还需要配合使用函数base64_encode。如下所示:

<code class="language-php hljs "><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getRandomString</span><span class="hljs-params">(<span class="hljs-variable">$length</span> = <span class="hljs-number">42</span>)</span>    {</span>        <span class="hljs-comment">/*         * Use OpenSSL (if available)         */</span>        <span class="hljs-keyword">if</span> (function_exists(<span class="hljs-string">'openssl_random_pseudo_bytes'</span>)) {            <span class="hljs-variable">$bytes</span> = openssl_random_pseudo_bytes(<span class="hljs-variable">$length</span> * <span class="hljs-number">2</span>);            <span class="hljs-keyword">if</span> (<span class="hljs-variable">$bytes</span> === <span class="hljs-keyword">false</span>)                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">'Unable to generate a random string'</span>);            <span class="hljs-keyword">return</span> substr(str_replace([<span class="hljs-string">'/'</span>, <span class="hljs-string">'+'</span>, <span class="hljs-string">'='</span>], <span class="hljs-string">''</span>, base64_encode(<span class="hljs-variable">$bytes</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);        }        <span class="hljs-variable">$pool</span> = <span class="hljs-string">'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</span>;        <span class="hljs-keyword">return</span> substr(str_shuffle(str_repeat(<span class="hljs-variable">$pool</span>, <span class="hljs-number">5</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);    }</code>

在调用base64_encode函数之后,还对结果进行了一次替换操作,目的是要去除随机生成的字符串中不需要的字符。

当然,在使用openssl_random_pseudo_bytes函数之前,最好使用function_exists来确保该函数在运行时是可用的。如果不可用,则使用Plan B:

<code class="language-php hljs ">substr(str_shuffle(str_repeat(<span class="hljs-variable">$pool</span>, <span class="hljs-number">5</span>)), <span class="hljs-number">0</span>, <span class="hljs-variable">$length</span>);</code>

这个函数的通用性很强,可以根据业务的需要进行适当修改然后当作静态方法进行调用。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn