首頁  >  文章  >  後端開發  >  PHP最強大的隨機字串產生函數

PHP最強大的隨機字串產生函數

angryTom
angryTom轉載
2019-10-14 18:35:092383瀏覽

在PHP中,尤其是網站程序,常常需要生成隨機密碼或字串,如微信的token,API密鑰,AppSecret 等等,使用下面的隨機字符串生成函數,便可以輕鬆生成你所需要的隨機字串。

程式碼如下:

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0){
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );
     
    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];
     
    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}

 更多PHP相關知識,請造訪PHP中文網

以上是PHP最強大的隨機字串產生函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:www.whmblog.cn。如有侵權,請聯絡admin@php.cn刪除