[PHP] uses openssl_random_pseudo_bytes and Base64_encode functions to generate random strings

Source: Internet
Author: User

The Openssl_random_pseudo_bytes function itself is used to generate a specified number of random bytes, so when you use it to generate random strings, you also need to use the function Base64_encode. As shown below:

 Public Static  function getrandomstring($length = ) {        /* * Use OpenSSL (if available) */        if(Function_exists (' Openssl_random_pseudo_bytes ')) {$bytes= Openssl_random_pseudo_bytes ($length*2);if($bytes===false)Throw NewRuntimeException (' Unable to generate a random string ');returnSUBSTR (Str_replace (['/',' + ',' = '],"', Base64_encode ($bytes)),0,$length); }$pool=' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';returnsubstr (Str_shuffle (Str_repeat ($pool,5)),0,$length); }

After calling the Base64_encode function, the result was also replaced once, in order to remove unwanted 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 run time. If not available, plan B is used:

substr(str_shuffle(str_repeat($pool50$length);

This function is very versatile, can be modified according to the needs of the business and then called as a static method.

[PHP] uses openssl_random_pseudo_bytes and Base64_encode functions to generate random strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.