PHP code example of corviz / csrf-token

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

    

corviz / csrf-token example snippets




use Corviz\CsrfToken\Token;

$token = new Token();
$tokenStr = $token->generate();
echo $tokenStr;




use Corviz\CsrfToken\Token;

$token = new Token();
$tokenStr = $_POST['csrf_token'];

if ($token->verify($tokenStr)) {
    //Valid token
} else {
    //Invalid token
}



use Corviz\CsrfToken\Token;

$token = new Token();
$identifier = 'form-1';

//Create new token string
$tokenStr = $token->generate($identifier);

//Verify incoming token string:
echo $token->verify($_POST['csrf_token'], $identifier) ? 'Valid csrf token' : 'Invalid csrf token';



use Corviz\CsrfToken\StorageInterface;

class DatabaseStorage implements StorageInterface
{
    public function get(string $key) : mixed
    {
        //read '$key' from db
    }

    public function set(string $key, mixed $value) : void
    {
        //write '$key' value to db
    }

    public function isset(string $key) : bool
    {
        //checks if $key exists in database
    }

    public function unset(string $key) : void
    {
        //delete $key from db
    }
}



use Corviz\CsrfToken\Token;

$token = new Token();
$storage = new DatabaseStorage();
$token->setStorage($storage);

echo $token->generate();



use Corviz\CsrfToken\Token;

$token = new Token();
$storage = new DatabaseStorage();
$token->setStorage($storage);

echo $token->verify($_POST['csrf_token']) ? 'Valid' : 'Invalid';



use Corviz\CsrfToken\KeyProviderInterface;
use \Corviz\CsrfToken\StorageInterface;

class MyKeyProvider implements KeyProviderInterface
{
    private StorageInterface $storage;
    
    public function generateKey() : string|false
    {
        $index = '...';
        
        if (!$this->storage->isset($index)) {
            // generate key and store it
            $hashKey = '...';
            $this->storage->set($index, $hashKey);
        }
        
        return $this->storage->get($index);
    }
    
    public function __construct(StorageInterface $storage) 
    {
        $this->storage = $storage;
    }
}



use Corviz\CsrfToken\Token;

$token = new Token();
$keyProvider = new MyKeyProvider($storage);
$token->setKeyProvider($keyProvider);

echo $token->generate();

//or 

echo $token->verify($_POST['csrf_token']) ? 'Valid' : 'Invalid';