random_int

(PHP 7, PHP 8)

random_intGet a cryptographically secure, uniformly selected integer

Descripción

random_int(int$min, int$max): int

Generates a uniformly selected integer between the given minimum and maximum.

The randomness generated by this function is suitable for all applications, including the generation of long-term secrets, such as encryption keys.

Las fuentes de aleatoriedad empleadas por esta función son las siguientes:

  • En Windows, se utilizará siempre » CryptGenRandom(). A partir de PHP 7.2.0, se usará siempre » CNG-API.
  • En Linux, se utilizará la llamada al sistema » getrandom(2) si está disponible.
  • En otras plataformas, se utilizará /dev/urandom.
  • Si no están disponibles ninguna de las fuentes citadas anteriormente, se lanzará una Exception.

Nota: Aunque esta función se añadió a PHP en PHP 7.0, hay disponible una » implementación de espacio de usuario para PHP 5.2 hasta 5.6, inclusive.

Parámetros

min

The lowest value to be returned.

max

The highest value to be returned.

Valores devueltos

A cryptographically secure, uniformly selected integer from the closed interval [min, max]. Both min and max are possible return values.

Errores/Excepciones

  • Si no se puede encontrar una fuente de aleatoriedad apropiada, se lanzará una Exception.
  • Si se proporcionan parámetros inválidos, se lanzará un TypeError.
  • If max is less than min, a ValueError will be thrown.

Historial de cambios

VersiónDescripción
8.2.0 In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

Ejemplos

Ejemplo #1 random_int() example

<?php
var_dump
(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

El resultado del ejemplo sería algo similar a:

int(248) int(-898)

Ver también

To Top