This question already has answers here:
PHP random string generator
                                
                                    (56个答案)
                                
                        
                                6年前关闭。
            
                    
您好,我想在PHP中像Ag7hlA这样的重复生成随机字符串。无论如何有做我正在尝试

<?php
function random_string($length)
{
    $length = (int) $length;
    if ($length < 1) return '';

    $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";
    $max = strlen($base) - 1;

    $string = '';
    while ($len--)
    {
        $string = $base[mt_rand(0, $max)];
    }
    return $string;
}
?>


但是没有生成随机字符串

最佳答案

function generateRandomString($length = 10) {
    $char = 'abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $char[rand(0, strlen($char) - 1)];
    }
    return $randomString;
}


如果您也要添加数字,则$char将是->

$char = 'abcdefghijklmnopqrstuvwxyz1234567890';


如果是大写案例->

$char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

10-08 02:38