PHP产生随机密码

原文链接: http://abeautifulsite.net/2008/05/generate-random-passwords-in-php/

Here is a function I wrote to generate a random string in PHP. It is probably most useful for generating passwords. You can specify the length of the resulting string, as well as what characters are allowed. The default length is eight and the default character set is alphanumeric.

function random_string($length = 8, $chars = null) {
    if( empty($chars) ) $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    while( strlen($s) < $length) {
        $s .= substr($chars, rand(0, strlen($chars) - 1), 1);
    }
    return $s;
}
// Example
echo random_string(10);

After improving:

you can specify "char range", such as : alpha only, number only or both of than. Also, you can append the array $char\_arr...

// ---------------------------------------------
// create pre-fixed width random string
// author: Roy@Gu
// date: 2009-12-5
//
function random_string($length = 8, $chars_range = 'alpha-number') {
    $str = '';
    $chars = '';
    $char_arr = array(
        "alpha" => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
        "number" => "0123456789",
    );
    if (empty($chars_range)) {
        $chars_rang = 'alpha-number';
    }
    if(strpos($chars_range, '-')) {
        $char_range_arr = explode('-',$chars_range);
        foreach($char_range_arr as $range){
            if(!array_key_exists($range, $char_arr)){
                exit("wrong range \"". $range ."\"");
            }
            $chars .= $char_arr[$range];
        }
    }else{
        if(!array_key_exists($chars_range, $char_arr)){
                exit("wrong range \"".$chars_range ."\"");
        }
        $chars = $char_arr[$chars_range];
    }
    while( strlen($str) < $length) {
        $str .= substr($chars, rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}