我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
$t = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
echo join('', array_map(function() use($t) { return $t[array_rand($t)]; }, range(1, 15)));
或一行程序
echo join('', array_map(function() { return substr('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', rand(0, 61), 1); }, range(1, 15)));
<?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 */
这将创建一个20个字符的十六进制字符串:
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
在PHP 7 (random_bytes())中:
$string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
// or
$string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
// or
$string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f
function rndStr($len = 64) {
$randomData = file_get_contents('/dev/urandom', false, null, 0, $len) . uniqid(mt_rand(), true);
$str = substr(str_replace(array('/','=','+'),'', base64_encode($randomData)),0,$len);
return $str;
}