Generate a Secure Random Number
Generates cryptographically secure random integers with `random_int()`, validates the requested range, and formats a short verification code.
Purpose
Generates cryptographically secure random integers with `random_int()`, validates the requested range, and formats a short verification code.
Snippet details
ContextSecurityLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Generate a Secure Random Number.
*
* Purpose:
* Uses `random_int()` for security-sensitive numbers such as verification
* codes, reset tokens, and one-time challenge values.
*
* @param int $minimum Lowest allowed number.
* @param int $maximum Highest allowed number.
* @return array Secure number and padded six-digit code.
*/
function ogSnippetGenerateASecureRandomNumber(int $minimum, int $maximum): array {
if ($minimum < 0) {
$minimum = 0;
}
if ($maximum <= $minimum) {
$maximum = $minimum + 999999;
}
$secure_number = random_int($minimum, $maximum);
$verification_code = str_pad((string) $secure_number, 6, '0', STR_PAD_LEFT);
return array(
'number' => $secure_number,
'verification_code' => $verification_code,
'range' => $minimum.'-'.$maximum
);
}
$gate_code = ogSnippetGenerateASecureRandomNumber(0, 999999);
echo 'Stargate challenge code: '.$gate_code['verification_code'];