declare(strict_types=1);
/**
* Generates a random 8-digit integer between 10,000,000 and 99,999,999 (inclusive).
* Guaranteed to start with a non-zero digit (1-9).
*
* @return int An 8-digit positive integer.
* @throws Exception If a cryptographically secure source of randomness is unavailable.
*/
function generate8DigitNumber(): int
{
// random_int($min, $max) is cryptographically secure and inclusive on both bounds.
return random_int(10_000_000, 99_999_999);
}
/**
* Generates an 8-character numeric string code between "00000000" and "99999999".
* Preserves leading zeros using sprintf, suitable for OTPs, PINs, or serial numbers.
*
* @return string An 8-character numeric string with leading zero padding if needed.
* @throws Exception If a cryptographically secure source of randomness is unavailable.
*/
function generate8DigitCode(): string
{
// Generate a value in the range [0, 99999999]
$rawValue = random_int(0, 99_999_999);
// Format as an 8-digit decimal string with leading zeros (%08d)
return sprintf('%08d', $rawValue);
}
// ==========================================
// Example Execution
// ==========================================
try {
// 1. Generate an 8-digit mathematical integer [10000000 to 99999999]
$randomNumber = generate8DigitNumber();
echo 'Generated 8-digit integer: ' . $randomNumber . PHP_EOL;
// 2. Generate an 8-character string code [00000000 to 99999999] preserving leading zeros
$randomCode = generate8DigitCode();
echo 'Generated 8-digit code string: ' . $randomCode . PHP_EOL;
} catch (Exception $e) {
// Exception thrown if OS lacks an adequate source of entropy
error_log('Error generating random number: ' . $e->getMessage());
}
/*
run:
Generated 8-digit integer: 59759711
Generated 8-digit code string: 33012698
*/