PHP code example of antikirra / token

1. Go to this page and download the library: Download antikirra/token library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

antikirra / token example snippets




declare(strict_types=1);

use Antikirra\Token;

final class MySecretToken extends Token
{
    protected static function type(): int
    {
        // Token type in the range from 1 to 255
        return 1;
    }

    protected static function salt(): string
    {
        // !!! DO NOT MODIFY AFTER SETUP !!!
        // Minimum 32 bytes w DateTimeImmutable('+1 day'));

// Get the encoded token string (URL-safe)
echo (string)$token;
// Output: AQBA4gEAAAAAAPDcoGguuFT3rMY17QZy-gmNOs1dIQWcR

// Decode and verify a token
$decoded = MySecretToken::decode('AQBA4gEAAAAAAPDcoGguuFT3rMY17QZy-gmNOs1dIQWcR');

// Check expiration
if ($decoded->isExpired()) {
    echo "Token has expired";
}

// Get token data
echo $decoded->getIdentity();   // 123456
echo $decoded->getExpiredAt()->format('Y-m-d H:i:s');

// Type checking
if ($decoded->typeOf(1)) {
    echo "This is a type 1 token";
}

// Serialization support
$serialized = serialize($token);
$unserialized = unserialize($serialized);
echo (string)$unserialized; // Same as original token

final class AccessToken extends Token
{
    protected static function type(): int { return 1; }
    protected static function salt(): string { return 'your-secret-salt-min-32-bytes-long-string-here'; }
    protected static function algorithm(): string { return 'sha3-256'; }
}

final class RefreshToken extends Token
{
    protected static function type(): int { return 2; }
    protected static function salt(): string { return 'different-salt-for-refresh-tokens-min-32-bytes'; }
    protected static function algorithm(): string { return 'sha3-256'; }
}

$access = AccessToken::create(userId: 42, expiredAt: new DateTimeImmutable('+15 minutes'));
$refresh = RefreshToken::create(userId: 42, expiredAt: new DateTimeImmutable('+30 days'));

try {
    $token = MySecretToken::decode('invalid-token-string');
} catch (RuntimeException $e) {
    // Handle invalid token (tampered, malformed, or expired signature)
    error_log("Token validation failed: " . $e->getMessage());
}