How to create a random string using PHP?

2019-01-04 08:34发布

I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:

Original string, 9 chars

$string = 'abcdefghi';

Example random string limiting to 6 chars

$string = 'ibfeca';

UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.

UPDATE: The function should generate any amount of chars as required.

Please comment the parts if you reply.

17条回答
做个烂人
2楼-- · 2019-01-04 08:41

A better and updated version of @taskamiski's excellent answer:

Better version, using mt_rand() instead of rand():

echo md5(mt_rand()); // 32 char string = 128bit

Even better, for longer strings, using the hash() function that allows to select hashing algorithmns:

echo hash('sha256', mt_rand()); // 64 char string
echo hash('sha512', mt_rand()); // 128 char string

If you want to cut the result down to let's say 50 chars, do it like this:

echo substr(hash('sha256', mt_rand()), 0, 50); // 50 char string
查看更多
Animai°情兽
3楼-- · 2019-01-04 08:42
// @author http://codeascraft.etsy.com/2012/07/19/better-random-numbers-in-php-using-devurandom/                                                
function devurandom_rand($min = 0, $max = 0x7FFFFFFF)
{
    $diff = $max - $min;
    if ($diff < 0 || $diff > 0x7FFFFFFF) {
        throw new RuntimeException('Bad range');
    }
    $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
    if ($bytes === false || strlen($bytes) != 4) {
        throw new RuntimeException('Unable to get 4 bytes');
    }
    $ary = unpack('Nint', $bytes);
    $val = $ary['int'] & 0x7FFFFFFF; // 32-bit safe                           
    $fp = (float) $val / 2147483647.0; // convert to [0,1]                          
    return round($fp * $diff) + $min;
}

function build_token($length = 60, $characters_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
    $map_length = mb_strlen($characters_map)-1;
    $token = '';
    while ($length--) {
        $token .= mb_substr($characters_map, devurandom_rand(0,$map_length),1);
    }
    return $token;
}

This will work only in UNIX environment where PHP is compiled with mcrypt.

查看更多
做个烂人
4楼-- · 2019-01-04 08:43

I think I will add my contribution here as well.

function random_string($length) {
    $bytes_1 = openssl_random_pseudo_bytes($length);
    $hex_1 = bin2hex($bytes_1);
    $random_numbers = substr(sha1(rand()), 0, $length);
    $bytes_2 = openssl_random_pseudo_bytes($length);
    $hex_2 = bin2hex($bytes_2);
    $combined_chars = $hex_1 . $random_numbers . $hex_2;
    $chars_crypted = hash('sha512', $combined_chars);

    return $chars_crypted;
}

Thanks

查看更多
Explosion°爆炸
5楼-- · 2019-01-04 08:43

you could make an array of characters then use rand() to pick a letter from the array and added it to a string.

$letters = array( [0] => 'a' [1] => 'b' [2] => 'c' [3] => 'd' ... [25] = 'z');

$lengthOfString = 10;
$str = '';

while( $lengthOfString-- )
{
   $str .= $letters[rand(0,25)];
}
echo $str;

*note that this does allow repeat characters

查看更多
女痞
6楼-- · 2019-01-04 08:47

Most aspects of this have already been discussed, but i'd recommend a slight update: If you are using this for retail usage, I would avoid the domain ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

and instead use: ABCDEFGHJKMNPQRSTUVWXY3456789

Granted, you end up with far fewer characters, but it saves a great deal of hassle, as customers cannot mistake 0 for O, or 1 for l or 2 for Z. Also, you can do an UPPER on the input and customers can then enter upper or lower case letters -- that is also sometimes confusing since they can look similar.

查看更多
Summer. ? 凉城
7楼-- · 2019-01-04 08:48

this will generate random string

function generateRandomString($length=10) {
    $original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
    $original_string = implode("", $original_string);
    return substr(str_shuffle($original_string), 0, $length);
}
echo generateRandomString(6);
查看更多
登录 后发表回答