random_bytes

(PHP 7)

random_bytesGenerates cryptographically secure pseudo-random bytes

Descrição

random_bytes ( int $length ) : string

Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

As fontes de aleatoriedade dessa função são:

  • No Windows, a função » CryptGenRandom() sempre será utilizada.
  • No Linux, a syscall » getrandom(2) será utilizada se disponível.
  • Em outras plataformas /dev/urandom será utilizada.
  • Se nenhuma das fontes acima estiver disponível, então uma Exception será lançada.

Nota: Embora essa função tenha sido adicionado no PHP 7.0, existe » implementação userland disponível para PHP 5.2 ao 5.6.

Parâmetros

length

The length of the random string that should be returned in bytes.

Valor Retornado

Returns a string containing the requested number of cryptographically secure random bytes.

Erros

  • Se uma fonte de aleatoriedade não for encontrada uma Exception será lançada.
  • No caso de parâmetros inválidos um TypeError será lançado.
  • If an invalid length of bytes is given, an Error will be thrown.

Exemplos

Exemplo #1 random_bytes() example

<?php
$bytes 
random_bytes(5);
var_dump(bin2hex($bytes));
?>

O exemplo acima irá imprimir algo similar à:

string(10) "385e33f741"

Veja Também