我试图在PHP中创建一个随机字符串,我得到绝对没有输出:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

PHP生成随机字符的函数

这个PHP函数为我工作:

function cvf_ps_generate_random_code($length=10) {

   $string = '';
   // You can define your own characters here.
   $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";

   for ($p = 0; $p < $length; $p++) {
       $string .= $characters[mt_rand(0, strlen($characters)-1)];
   }

   return $string;

}

用法:

echo cvf_ps_generate_random_code(5);

其他回答

递归解决方案:

public static function _random(string $set , int $length): string
{
    $setLength = strlen($set);
    $randomKey = random_int(0, $setLength - 1);

    $firstPiece = substr($set, 0, $randomKey);
    $secondPiece = substr($set, $randomKey, $setLength - $randomKey);

    $removedCharacter = $firstPiece[strlen($firstPiece) - 1] ?? null;
    if(null === $removedCharacter || $length === 0) {
        return '';
    }
    $firstPieceWithoutTheLastChar = substr($firstPiece, 0, -1);

    return $removedCharacter . self::_random($firstPieceWithoutTheLastChar . $secondPiece, $length - 1);
}

不错的表现,https://3v4l.org/aXaJ6/perf

@tasmaniski:你的答案对我有用。我也有同样的问题,我想把它推荐给那些一直在寻找同样答案的人。以下是来自@tasmaniski的留言:

<?php 
    $random = substr(md5(mt_rand()), 0, 7);
    echo $random;
?>

这是一个youtube视频,向我们展示如何创建一个随机数

如果您在用户可能看到或使用它的地方使用这个随机字符串(例如作为密码生成器),您可能希望限制用于排除元音的字符集。这样你就不会不小心说脏话,也不会冒犯别人。别笑,这是常有的事。

function gen_uid($l=5){
   return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 10, $l);
}
echo gen_uid();

默认值[5]:WvPJz

echo gen_uid(30);

价值[30]:cAiGgtf1lDpFWoVwjykNKXxv6SC4Q2

这个问题有很多答案,但没有一个是利用加密安全伪随机数生成器(CSPRNG)的。

简单、安全、正确的答案是使用RandomLib,不要白费力气。

对于那些坚持发明自己的解决方案的人,PHP 7.0.0将为此目的提供random_int();如果你还在使用PHP 5。x,我们为random_int()写了一个PHP 5的polyfill,这样你甚至可以在升级到PHP 7之前使用新的API。

在PHP中安全地生成随机整数并不是一项简单的任务。在生产环境中部署自己开发的算法之前,您应该始终与常驻StackExchange密码学专家进行检查。

有了安全的整数生成器,使用CSPRNG生成随机字符串就像在公园里散步一样简单。

创建安全的随机字符串

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 *
 * This function uses type hints now (PHP 7+ only), but it was originally
 * written for PHP 5 as well.
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    int $length = 64,
    string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
    if ($length < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $pieces = [];
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pieces []= $keyspace[random_int(0, $max)];
    }
    return implode('', $pieces);
}

用法:

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();

演示:https://3v4l.org/IMJGF(忽略PHP 5失败;它需要random_compat)