php生成随机字符串

<?php
function RandomString($length=32,$type='number',$sa=''){
    $string='';
    switch($type){
        //纯小写英文字母,RandomString(32,'string')
        case 'string':
            $sa='abcdefghijklmnopqrstuvwxyz';
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,25)];}
            unset($length,$type,$sa);
            break;
        //纯大写英文字母,RandomString(32,'STRING')
        case 'STRING':
            $sa='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,25)];}
            unset($length,$type,$sa);
            break;
        //大小写英文字母,RandomString(32,'String')
        case 'String':
            $sa='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,51)];}
            unset($length,$type,$sa);
            break;
        //常用字符,RandomString(32,'full')
        case 'full':
            $sa='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~0)1!2@3#4$5%6^7&8*9(-_=+';
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,77)];}
            unset($length,$type,$sa);
            break;
        //全字符,RandomString(32,'Full')
        case 'Full':
            $sa='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~0)1!2@3#4$5%6^7&8*9(-_=+[{]},<.>/?\|';
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,89)];}
            unset($length,$type,$sa);
            break;
        //自定义,RandomString(32,'custom','abcdefABCDEF123456!@#$%^')
        case 'custom':
            $sal=strlen($sa)-1;
            for($i=0;$i<$length;$i++){$string=$string.$sa[rand(0,$sal)];}
            unset($length,$type,$sa,$sal);
            break;
        //纯数字,RandomString(32,'custom','abcdefABCDEF123456!@#$%^')
        case 'number':
        default:
            for($i=0;$i<$length;$i++){$string=$string.rand(0,9);}
            unset($length,$type,$sa);
            break;
    }
    return $string;
}
?>

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!