One Time Code Generator
Creates numeric or alphanumeric one-time codes with expiration and attempt limits.
Function signature
ogCreateOneTimeCode(length = 6, ttl_seconds = 600, scope = 'default', mode = 'numeric')
Categories
- Sessions and Authentication
Parameters
lengthCode length.ttl_secondsNumber of seconds before expiration.scopeCode scope label.modeCode mode: numeric or alphanumeric.Return value
Short public-safe status message.
- code
- code_hash
- scope
- expires_at
- max_attempts
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets out of public output.
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.
*/
/**
* Creates numeric or alphanumeric one-time codes with expiration and attempt limits.
*
* Primary use case: Email verification, account recovery, admin confirmation.
* Typical inputs: length, charset, ttl, scope.
* Typical output: code plus hashed storage value.
*
* Implementation note: Store hashed code, not plaintext code.
*
* @param int $length Code length.
* @param int $ttl_seconds Number of seconds before expiration.
* @param string $scope Code scope label.
* @param string $mode Code mode: numeric or alphanumeric.
* @return array Structured result data with success, message, and data keys.
*/
function ogCreateOneTimeCode($length = 6, $ttl_seconds = 600, $scope = 'default', $mode = 'numeric') {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$length = (int)$length;
$ttl_seconds = (int)$ttl_seconds;
$scope = trim((string)$scope);
$mode = trim((string)$mode);
if ($length < 4) {
$length = 4;
}
if ($length > 32) {
$length = 32;
}
if ($ttl_seconds < 60) {
$ttl_seconds = 60;
}
if (empty($scope)) {
$scope = 'default';
}
$code = '';
if ($mode == 'alphanumeric') {
$characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$max_index = strlen($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$code .= $characters[random_int(0, $max_index)];
}
} else {
$max = (int)pow(10, $length) - 1;
$min = (int)pow(10, $length - 1);
$code = (string)random_int($min, $max);
}
$result['success'] = true;
$result['message'] = 'One-time code created.';
$result['data'] = array(
'code' => $code,
'code_hash' => password_hash($code, PASSWORD_DEFAULT),
'scope' => $scope,
'expires_at' => time() + $ttl_seconds,
'max_attempts' => 5
);
return $result;
}