我试图在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具有最高质量的伪随机性,此时它可以是v5、v6、v7或v8,并且可以使用默认配置或特殊配置。为了解决这种混乱,我在这里选取了其他几个答案,并包含了函数可用性条件。

使用。要全局使用它,给$VALID_ID_CHARS赋值你想要的字符,然后调用它:

$VALID_ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$myNewRandomId = makeId(6);
function makeId($desiredLen)
{
    global $VALID_ID_CHARS;
    if ($desiredLen < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $vLen = 0;
    if (function_exists('mb_strlen')) {
        $vLen = mb_strlen($VALID_ID_CHARS, '8bit') - 1;
    } else {
        $vLen = strlen($VALID_ID_CHARS) - 1;
    }
    if (function_exists('random_int')) {
        $pieces = [];
        for ($i = 0; $i < $desiredLen; ++$i) {
            $pieces[] = $VALID_ID_CHARS[random_int(0, $vLen)];
        }
        return implode('', $pieces);
    }
    if (function_exists('openssl_random_pseudo_bytes')) {
        $random = openssl_random_pseudo_bytes($desiredLen);
        $id = '';
        for ($i = 0; $i < $desiredLen; ++$i) {
            $id .= $VALID_ID_CHARS[ord($random[$i]) % $vLen];
        }
        return $id;
    }
    http_response_code(500);
    die('random id generation failed. either random_int or openssl_random_pseudo_bytes is needed');
}

其他回答

function getRandomString($length) {
  $salt = array_merge(range('a', 'z'), range(0, 9));
  $maxIndex = count($salt) - 1;

  $result = '';
  for ($i = 0; $i < $length; $i++) {
    $index = mt_rand(0, $maxIndex);
    $result .= $salt[$index];
  }
  return $result
}

你完全做错了,因为你依赖于数字,而不是字符,我不确定如果你想要随机输出只是数字,如果是这样,为什么需要得到所有的字母和所有的数字,并提取它们的长度?为什么不用rand(0,62)呢?,即使你在声明函数之前忘记初始化变量$randstring。

不管怎样,PHP为此目的提供了一个非常方便的函数。它的作用是()。下面是一个适合您需要的例子。

< ?php 函数随机字符串(){ $字符= '0123456789abcdefghijklmnopqrstuvwxyz '; 返回str_shuffle($字符); } echo randomString ();

从php7开始,就有了random_bytes函数。 https://www.php.net/manual/ru/function.random-bytes.php 你可以生成一个这样的随机字符串

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

你可以试试这个:

<?php
    function random($len){

        $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        // ----------------------------------------------
        // Number of possible combinations
        // ----------------------------------------------
        $pos = strlen($char);
        $pos = pow($pos, $len);
        echo $pos.'<br>';
        // ----------------------------------------------

        $total = strlen($char)-1;
        $text = "";

        for ($i=0; $i<$len; $i++){
            $text = $text.$char[rand(0, $total)];
        }
        return $text;
    }

    $string = random(15);
    echo $string;
?>

您也可以准时使用md5,但要小心。

您需要使用microtime()而不是time()函数,因为如果多个线程在同一秒内运行,则需要为所有线程获取不同的字符串。

<?php

    $string = md5(microtime());
    echo $string;
?>
<?php
    /**
     * Creates a random string
     *
     * @param (int) $length
     *   Length in characters
     * @param (array) $ranges
     *   (optional) Array of ranges to be used
     *
     * @return
     * Random string
    */
    function random_string($length, $ranges = array('0-9', 'a-z', 'A-Z')) {
        foreach ($ranges as $r) $s .= implode(range(array_shift($r = explode('-', $r)), $r[1]));
        while (strlen($s) < $length) $s .= $s;
        return substr(str_shuffle($s), 0, $length);
    }

    // Examples:
    $l = 100;
    echo '<b>Default:</b> ' . random_string($l) . '<br />';
    echo '<b>Lower Case only:</b> ' . random_string($l, array('a-z')) . '<br />';
    echo '<b>HEX only:</b> ' . random_string($l, array('0-9', 'A-F')) . '<br />';
    echo '<b>BIN only:</b> ' . random_string($l, array('0-1')) . '<br />';

/* End of file */