PHP code example of adbario / slim-csrf

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

    

adbario / slim-csrf example snippets


$container['session'] = function ($container) {
    return new \Adbar\Session(
        $container->get('settings')['session']['namespace']
    );
};

$container['csrf'] = function ($c) {
    return new \Adbar\Slim\Csrf($c->get('session'));
};

$container['csrf'] = function ($c) {
    return new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
};

$app->add(new \Adbar\SessionMiddleware($container->get('settings')['session']));

/** Csrf */
$app->add($app->getContainer()->get('csrf'));

/** Session */
$app->add(new \Adbar\SessionMiddleware($container->get('settings')['session']));

$app->get('/form', function ($request, $response) {
    // CSRF token will be added
    return $this->view->render($response, 'form.twig');
})->add($container->get('csrf'));

$app->post('/form', function ($request, $response) {
    // If CSRF token was valid, code after this will run
})->add($container->get('csrf'));

<form method="post">
    <?= $csrf 

$container['csrf'] = function () {
    return new \Adbar\Slim\Csrf;
};

$app->get('/form', function ($request, $response) {
    // Generate form field
    $csrf = $this->csrf->generateForm();
    // Inject form field to your view...
});

$container['csrf'] = function ($c) {
    $csrf = new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
    $csrf->setTokenError(function ($request, $response, $next) use ($c) {
        return $c->view->render($response->withStatus(400), 'csrf_error.twig');
    });
    return $csrf;
};

$container['csrf'] = function ($c) {
    $csrf = new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
    $csrf->setTokenErrorMessage('This is my custom error message.');
    return $csrf;
};