[PHP]利用openssl_random_pseudo_bytes和base64_encode函數來產生隨機字串

來源:互聯網
上載者:User
openssl_random_pseudo_bytes函數本身是用來產生指定個數的隨機位元組,因此在使用它來產生隨機字串時,還需要配合使用函數base64_encode。如下所示:

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);    }

在調用base64_encode函數之後,還對結果進行了一次替換操作,目的是要去除隨機產生的字串中不需要的字元。

當然,在使用openssl_random_pseudo_bytes函數之前,最好使用function_exists來確保該函數在運行時是可用的。如果不可用,則使用Plan B:

substr(str_shuffle(str_repeat($pool, 5)), 0, $length);

這個函數的通用性很強,可以根據業務的需要進行適當修改然後當作靜態方法進行調用。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.