[PHP]利用openssl_random_pseudo_bytes和base64_encode函數來產生隨機字串
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);
這個函數的通用性很強,可以根據業務的需要進行適當修改然後當作靜態方法進行調用。
http://www.bkjia.com/PHPjc/981960.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/981960.htmlTechArticle[PHP]利用openssl_random_pseudo_bytes和base64_encode函數來產生隨機字串 openssl_random_pseudo_bytes函數本身是用來產生指定個數的隨機位元組,因此在使用...