random_bytes

函式
random_bytes ( $bytes )
引數
  • (int) $bytes
    Required:
返回值
  • (string)
定義位置
相關方法
random_intdo_robotsdo_meta_boxesrandomcompat_strlenrandomcompat_substr
引入
-
棄用
-

random_bytes: 這是一個PHP函式,用於生成一個隨機的位元組字串。它可以用於密碼學目的或生成隨機資料。

由ext/mcrypt提供支援(幸好不是libmcrypt)。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function random_bytes($bytes)
{
try {
/** @var int $bytes */
$bytes = RandomCompat_intval($bytes);
} catch (TypeError $ex) {
throw new TypeError(
'random_bytes(): $bytes must be an integer'
);
}
if ($bytes < 1) {
throw new Error(
'Length must be greater than 0'
);
}
/** @var string|bool $buf */
$buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM);
if (
is_string($buf)
&&
RandomCompat_strlen($buf) === $bytes
) {
/**
* Return our random entropy buffer here:
*/
return $buf;
}
/**
* If we reach here, PHP has failed us.
*/
throw new Exception(
'Could not gather sufficient random data'
);
}
}
function random_bytes($bytes) { try { /** @var int $bytes */ $bytes = RandomCompat_intval($bytes); } catch (TypeError $ex) { throw new TypeError( 'random_bytes(): $bytes must be an integer' ); } if ($bytes < 1) { throw new Error( 'Length must be greater than 0' ); } /** @var string|bool $buf */ $buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM); if ( is_string($buf) && RandomCompat_strlen($buf) === $bytes ) { /** * Return our random entropy buffer here: */ return $buf; } /** * If we reach here, PHP has failed us. */ throw new Exception( 'Could not gather sufficient random data' ); } }
function random_bytes($bytes)
    {
        try {
            /** @var int $bytes */
            $bytes = RandomCompat_intval($bytes);
        } catch (TypeError $ex) {
            throw new TypeError(
                'random_bytes(): $bytes must be an integer'
            );
        }

        if ($bytes < 1) {
            throw new Error(
                'Length must be greater than 0'
            );
        }

        /** @var string|bool $buf */
        $buf = @mcrypt_create_iv((int) $bytes, (int) MCRYPT_DEV_URANDOM);
        if (
            is_string($buf)
                &&
            RandomCompat_strlen($buf) === $bytes
        ) {
            /**
             * Return our random entropy buffer here:
             */
            return $buf;
        }

        /**
         * If we reach here, PHP has failed us.
         */
        throw new Exception(
            'Could not gather sufficient random data'
        );
    }
}

常見問題

FAQs
檢視更多 >