PHP code example of mmdm / sim-csrf

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

    

mmdm / sim-csrf example snippets

 
composer 



// to instance a csrf object
$csrf = new Csrf();
// then use csrf mothods like
$field = $csrf->getField();
// the output will be
// <input type="hidden" name="csrftoken" value="generated token">

// to set token expiration
$csrf->setExpiration(10);
// token is valid just for 10 seconds from now
// after 10 seconds it'll be generate again

$token1 = $csrf->getToken();
// some code
// ...
$token2 = $csrf->getToken();
// some othe code
// ...
$token3 = $csrf->getToken();

$token1 = $csrf->setExpiration(20)->getToken();
// some code
// ...
// in this code, expiration time will be 20 seconds
//according to previous codes
// if you want anothe expiration, specify it then
$token2 = $csrf->setExpiration(300)->getToken();
// some othe code
// ...
// same thing here
$token3 = $csrf->getToken();

// an integer value in seconds like 300
$timeout = $csrf->getExpiration();

// returns filed string for form
$field = $csrf->getField();
// output is
// <input type="hidden" name="csrftoken" value="generated token">

// returns token string
$token = $csrf->getToken();
// output is a hashed string

// returns token string
$token = $csrf->regenerateToken();
// output is a hashed string

// returns true on valid and false otherwise
$isValid = $csrf->validate();

// to clear all tokens
$csrf->clear();

interface ICsrfStorage
{
    /**
     * @param $key
     * @param $value
     * @param $time
     * @return ICsrfStorage
     */
    public function set($key, $value, $time): ICsrfStorage;

    /**
     * @param $key
     * @return mixed
     */
    public function get($key);

    /**
     * @param $key
     * @return bool
     */
    public function has($key): bool;

    /**
     * @param $key
     * @return ICsrfStorage
     */
    public function remove($key): ICsrfStorage;

    /**
     * Extend CSRF timeout if you want to
     *
     * @param $key
     * @param int $expiration
     * @return ICsrfStorage
     */
    public function extend($key, int $expiration): ICsrfStorage;

    /**
     * Remove all stored tokens
     *
     * @param string $prefix
     * @return ICsrfStorage
     */
    public function clear($prefix): ICsrfStorage;
}