Zero-dependency RFC 4226 HOTP and RFC 6238 TOTP two-factor authentication (2FA) library for HolyPHP, featuring Base32 encoding/decoding, clock-drift window verification, and otpauth:// URI generation.
bundled — works offlinezero dependencieshotpotp
Quick start
import "totp";
$secret = "JBSWY3DPEHPK3PXP";
// Generate a 6-digit TOTP code for the current 30-second window
$code = totp_generate($secret);
println("Current TOTP: " . $code);
// Verify a user-supplied code (allowing ±1 time step of clock drift)
if (totp_verify($secret, $code)) {
println("Code is valid!");
}
// Build an otpauth:// URI for QR code provisioning
$uri = totp_uri($secret, "alice@example.com", "MyApp");
println("Provisioning URI: " . $uri);
$issuer: Optional service/issuer name (e.g., "MyApp").
$period: Time step in seconds (must be > 0). Defaults to 30.
$digits: Number of digits (6–8). Defaults to 6.
Returns: URL-encoded otpauth://totp/... URI string.
totp_base32_decode(string $secret): array
Decodes an RFC 4648 Base32 string into an array of byte integers (0–255). Ignores whitespace, hyphens, and trailing = padding, and is case-insensitive.
totp_base32_encode(string $data): string
Encodes a raw byte string into an uppercase unpadded Base32 string.
Error Handling
All functions validate their inputs and throw Exception with clear, actionable messages prefixed with totp::
Empty secret: totp: secret must not be empty
Invalid Base32 character: totp: invalid Base32 character '1' at position 8
Secret too short: totp: Base32 secret is too short to decode any bytes
Invalid digits: totp: digits must be between 6 and 8, got 5
Invalid period: totp: period must be a positive integer, got 0
Negative counter: totp: counter must be non-negative, got -1
Negative timestamp: totp: timestamp must be non-negative, got -5
Negative window: totp: window must be non-negative, got -1
Empty account in URI: totp: account name must not be empty
Bundled with the compiler — import "totp"; works offline in any file, or add it to a project with hphp install totp.
import "totp";
$secret = "JBSWY3DPEHPK3PXP";
// Generate a 6-digit TOTP code for the current 30-second window
$code = totp_generate($secret);
println("Current TOTP: " . $code);
// Verify a user-supplied code (allowing ±1 time step of clock drift)
if (totp_verify($secret, $code)) {
println("Code is valid!");
}
// Build an otpauth:// URI for QR code provisioning
$uri = totp_uri($secret, "alice@example.com", "MyApp");
println("Provisioning URI: " . $uri);
Try it
hphp install totp
hphp run main.hphp
Covered by the official test suite in tests/positive/lib_totp.hphp.