Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

random_bytes()

Generate the requested number of cryptographically secure random bytes.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

random_bytes(int $length): string

Generate the requested number of cryptographically secure random bytes. The result is binary and may contain null bytes. Hex encoding doubles its byte length. Lengths below one raise ValueError, and an unavailable randomness source raises Random\RandomException on PHP 8.4.

Signature

random_bytes(int $length): string

Example output

16 32
ValueError

Examples

<?php
$bytes=random_bytes(16);
echo strlen($bytes), " ", strlen(bin2hex($bytes)), "\n";
try { random_bytes(0); } catch (ValueError $e) { echo get_class($e); }

Result

16 32
ValueError

Sources