Skip to content

Instantly share code, notes, and snippets.

@lepig
Last active May 22, 2020 14:13
Show Gist options
  • Save lepig/377cdebc7fad27e1376f97f4f522c8b5 to your computer and use it in GitHub Desktop.
Save lepig/377cdebc7fad27e1376f97f4f522c8b5 to your computer and use it in GitHub Desktop.
读取/dev/urandom获取随机数
<?php
/**
* 读取/dev/urandom获取随机数
* @param $len
* @return mixed|string
*/
function randomFromDev($len) {
$fp = @fopen('/dev/urandom','rb');
$result = '';
if ($fp !== FALSE) {
$result .= @fread($fp, $len);
@fclose($fp);
}
else
{
trigger_error('Can not open /dev/urandom.');
}
// convert from binary to string
$result = base64_encode($result);
// remove none url chars
$result = strtr($result, '+/', '-_');
return substr($result, 0, $len);
}
<?php
function randomFromDev($len)
{
$fp = @fopen('/dev/urandom','rb');
$result = '';
if ($fp !== FALSE) {
$result .= @fread($fp, $len);
@fclose($fp);
}
else
{
trigger_error('Can not open /dev/urandom.');
}
// convert from binary to string
$result = base64_encode($result);
// remove none url chars
$result = strtr($result, '+/', '-_');
// Remove = from the end
$result = str_replace('=', ' ', $result);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment