PHP code example of schnittstabil / csrf-twig-helpers

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

    

schnittstabil / csrf-twig-helpers example snippets



/**
 * Some callable, which is used to get csrf tokens. E.g:
 */
function getToken() {
    if (!isset($_SESSION['csrf_token'])) {
        // generate a new token...
    }

    return $_SESSION['csrf_token'];
}

$twig = new Twig_Environment($loader);

$twig->addExtension(
    new Schnittstabil\Csrf\Twig\Helpers\Extension(getToken, 'X-XSRF-TOKEN')
);


/* index.php */
r7\Csrf\MiddlewareBuilder as CsrfMiddlewareBuilder;

/**
 * Create App
 */
$app = new Slim\App();

/**
 * Register Csrf Middleware
 */
$app->getContainer()['csrf'] = function ($c) {
    $key = 'This key is not so secret - change it!';

    return CsrfMiddlewareBuilder::create($key)
        ->buildSynchronizerTokenPatternMiddleware();
};
$app->add('csrf');

/**
 * Register Twig Extensions
 */
$app->getContainer()['view'] = function ($c) {
    $view = new Slim\Views\Twig('templates', [
        'cache' => 'cache',
    ]);
    $view->addExtension(new Slim\Views\TwigExtension(
        $c['router'],
        $c['request']->getUri()
    ));
    $view->addExtension(new Schnittstabil\Csrf\Twig\Helpers\Extension(
        [$c['csrf']->getTokenService(), 'generate']
    ));

    return $view;
};

/**
 * Add routes
 */
$app->get('/', function ($request, $response) {
    return $this->view->render($response, 'index.html.twig');
});

$app->post('/contact', function ($request, $response) {
    return $this->view->render($response, 'contact.html.twig');
})->setName('contact');

/**
 * Run app
 */
$app->run();