[PHP] use the openssl_random_pseudo _ bytes and base64_encode functions to generate random strings

Source: Internet
Author: User
[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.

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.