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

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

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

//generateRandomString http://stackoverflow.com/questions/4356289/php-random-string-generator
function randomString($length = 32, $string= "0123456789abcdefghijklmnopqrstuvwxyz" ) {
    //$string can be:
    //0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    //0123456789abcdefghijklmnopqrstuvwxyz
    return substr(str_shuffle( $string), 0, $length);
}

其他回答

使用random_bytes函数生成加密安全的随机字节。

$bytes = random_bytes(16);
echo bin2hex($bytes);

可能的输出

da821217e61e33ed4b2dd96f8439056c

使用openssl_random_pseudo_bytes函数生成伪随机字节。

$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes);

可能的输出

e2d1254506fbb6cd842cd640333214ad

最好的用例是

function getRandomBytes($length = 16)
{
    if (function_exists('random_bytes')) {
        $bytes = random_bytes($length / 2);
    } else {
        $bytes = openssl_random_pseudo_bytes($length / 2);
    }
    return bin2hex($bytes);
}
echo getRandomBytes();

可能的输出

ba8cc342bdf91143

以前的答案会生成不安全或难以输入的密码。

这是安全的,并且提供了用户更有可能实际使用的密码,而不是因为一些薄弱的东西而被丢弃。

// NOTE: On PHP 5.x you will need to install https://github.com/paragonie/random_compat

/**
 * Generate a password that can easily be typed by users.
 *
 * By default, this will sacrifice strength by skipping characters that can cause
 * confusion. Set $allowAmbiguous to allow these characters.
 */
static public function generatePassword($length=12, $mixedCase=true, $numericCount=2, $symbolCount=1, $allowAmbiguous=false, $allowRepeatingCharacters=false)
{
  // sanity check to prevent endless loop
  if ($numericCount + $symbolCount > $length) {
    throw new \Exception('generatePassword(): $numericCount + $symbolCount are too high');
  }

  // generate a basic password with just alphabetic characters
  $chars  = 'qwertyupasdfghjkzxcvbnm';
  if ($mixedCase) {
    $chars .= 'QWERTYUPASDFGHJKZXCVBNML';
  }
  if ($allowAmbiguous) {
    $chars .= 'iol';
    if ($mixedCase) {
      $chars .= 'IO';
    }
  }

  $password = '';
  foreach (range(1, $length) as $index) {
    $char = $chars[random_int(0, strlen($chars) - 1)];

    if (!$allowRepeatingCharacters) {
      while ($char == substr($password, -1)) {
        $char = $chars[random_int(0, strlen($chars) - 1)];
      }
    }

    $password .= $char;
  }


  // add numeric characters
  $takenSubstitutionIndexes = [];

  if ($numericCount > 0) {
    $chars = '23456789';
    if ($allowAmbiguous) {
      $chars .= '10';
    }

    foreach (range(1, $numericCount) as $_) {
      $index = random_int(0, strlen($password) - 1);
      while (in_array($index, $takenSubstitutionIndexes)) {
        $index = random_int(0, strlen($password) - 1);
      }

      $char = $chars[random_int(0, strlen($chars) - 1)];
      if (!$allowRepeatingCharacters) {
        while (substr($password, $index - 1, 1) == $char || substr($password, $index + 1, 1) == $char) {
          $char = $chars[random_int(0, strlen($chars) - 1)];
        }
      }

      $password[$index] = $char;
      $takenSubstitutionIndexes[] = $index;
    }
  }

  // add symbols
  $chars = '!@#$%&*=+?';
  if ($allowAmbiguous) {
    $chars .= '^~-_()[{]};:|\\/,.\'"`<>';
  }

  if ($symbolCount > 0) {
    foreach (range(1, $symbolCount) as $_) {
      $index = random_int(0, strlen($password) - 1);
      while (in_array($index, $takenSubstitutionIndexes)) {
        $index = random_int(0, strlen($password) - 1);
      }

      $char = $chars[random_int(0, strlen($chars) - 1)];
      if (!$allowRepeatingCharacters) {
        while (substr($password, $index - 1, 1) == $char || substr($password, $index + 1, 1) == $char) {
          $char = $chars[random_int(0, strlen($chars) - 1)];
        }
      }

      $password[$index] = $char;
      $takenSubstitutionIndexes[] = $index;
    }
  }

  return $password;
}

我想要特定字符和预设长度的伪随机字符串。我希望当前版本的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');
}

这一个是从管理员来源:

/** Get a random string
* @return string 32 hexadecimal characters
*/
function rand_string() {
    return md5(uniqid(mt_rand(), true));
}

管理员,用PHP编写的数据库管理工具。

这段代码将帮助:

此函数将返回长度在$maxLength和$minLength之间的随机字符串。

注意:函数random_bytes从PHP 7开始工作。

如果你需要特定的长度,那么$maxLength和$minLength必须相同。

function getRandomString($maxLength = 20, $minLength = 10)
{
    $minLength = $maxLength < $minLength ? $maxLength : $minLength;
    $halfMin = ceil($minLength / 2);
    $halfMax = ceil($maxLength / 2);
    $bytes = random_bytes(rand($halfMin, $halfMax));
    $randomString = bin2hex($bytes);
    $randomString = strlen($randomString) > $maxLength ? substr($randomString, 0, -1) : $randomString;
    return $randomString;
}