PHP隨機函數【上】


隨機函數應用的場景很多,比如驗證碼,token,訂單號等。由淺入深了解常用隨機函數

1.rand

常用的隨機數字函數,默認生成[0,getrandmax()]之間的隨機數(包括邊界值),因性能問題已被mt_rand替換。

相關函數:rand(int $min, int $max)生成$min和$max之間的數。

     srand(int $seed) 生成時間種子,同一個時間種子下隨機生成的隨機值相同。

     getrandmax() 獲取最大隨機數(隨系統不同而不同)。

使用場景:見mt_rand

2.mt_rand

常用隨機函數,默認生成[0,mt_getrandmax()]之間的隨機函數(包括邊界值).

相關函數:mt_rand(int $min, int $max)生成$min和$max之間的數。

     mt_srand(int $seed) 生成時間種子,同一個時間種子下隨機生成的隨機值相同。

     mt_getrandmax() 獲取最大隨機數(隨系統不同而不同)。

使用場景:生成驗證碼mt_rand(1000, 9999);

     生成訂單號date('YmdHis').str_pad(mt_rand(1,99999), 5, '0', STR_PAD_LEFT);

3.uniqid

生成唯一ID的函數,精確到了微妙,較mt_rand精確。

相關函數:uniqid([string $prefix = "" [, bool $more_entropy = false ]]) 前綴可用在多個腳本生成ID重復問題,正常返回13位,加密后返回23位

使用場景:生成token md5(uniqid())

     生成uuid 

function guid(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
                .substr($charid, 0, 8).$hyphen
                .substr($charid, 8, 4).$hyphen
                .substr($charid,12, 4).$hyphen
                .substr($charid,16, 4).$hyphen
                .substr($charid,20,12)
                .chr(125);// "}"
        return $uuid;
    }
}
echo guid();

4.openssl_random_pseudo_bytes

函數

使用場景:生成token

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

5.linux下

head /dev/urandom | tr -dc a-z0-9 | head -c 20

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM