PHP code example of tuupola / branca

1. Go to this page and download the library: Download tuupola/branca 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/ */

    

tuupola / branca example snippets


use Branca\Branca;

$key = random_bytes(32);
$branca = new Branca($key);

$payload = "[email protected]";
$token = $branca->encode($payload);
/* hGgg0dPSseaUPZqGloWlDGb2i8hb6iamFBIQaatgYDRhEuaXyByaX0nzmyQk1WYAuSBEMWpB20Z1dENLFItwf1 */

$decoded = $branca->decode($token);
/* [email protected] */

use Branca\Branca;

$key = random_bytes(32);
$branca = new Branca($key);

$payload = json_encode(["scope" => ["read", "write", "delete"]]);
$token = $branca->encode($payload);

/*
5R7p5pC1gU5kfVuBUzhl43Ndh4HLT9fxAHrhN1zNRivTuehY8zYYzrVZ8C6d6VcNLfCk3EUgBwwW6kIk0wm32O34OFIYz5LnOIezwcV2Xsfc
*/

$decoded = $branca->decode($token);
$array = json_decode($decoded, true);

/*
Array
(
    [scope] => Array
        (
            [0] => read
            [1] => write
            [2] => delete
        )

)
*/

use Branca\Branca;
use MessagePack\MessagePack;
use MessagePack\Packer;
use MessagePack\BufferUnpacker;

$key = random_bytes(32);
$branca = new Branca($key);

$payload = (new Packer)->pack(["scope" => ["read", "write", "delete"]]);
$token = $branca->encode($payload);

/*
3iJt0CjqTRh3FGuAf0DHEmhULFIbPVInjguWIkmyCm7RMps5BMJZKa1KwZMN0z58IpPeCxdjoTdkurn9pl0YNrxAQfg3deP0
*/

$decoded = $branca->decode($token);
$unpacked = (new BufferUnpacker($decoded))->unpack();
print_r($unpacked);

/*
Array
(
    [scope] => Array
        (
            [0] => read
            [1] => write
            [2] => delete
        )

)
*/

use Branca\Branca;

$key = hex2bin("73757065727365637265746b6579796f7573686f756c646e6f74636f6d6d6974");
$branca = new Branca($key);

$token = "1jJDJOEeG2FutA8g7NAOHK4Mh5RIE8jtbXd63uYbrFDSR06dtQl9o2gZYhBa36nZHXVfiGFz";

print $branca->timestamp($token); /* 123206400 */

try {
    $decoded = $branca->decode($token, 3600);
} catch (RuntimeException $exception) {
    print $exception->getMessage(); /* Token is expired */
}