PHP code example of aurmil / slim3-csrf-utilities

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

    

aurmil / slim3-csrf-utilities example snippets





// declare usage of needed classes
use Aurmil\Slim\CsrfTokenToView;
use Aurmil\Slim\CsrfTokenToHeaders;

// Composer autoload file
a route needs a view renderer
$container['renderer'] = function ($c) {
    return new \Slim\Views\Twig(__DIR__, ['cache' => false]); // Twig
    return new \Slim\Views\PhpRenderer(__DIR__.'/'); // Or PHP
};

// CSRF component
$container['csrf'] = function ($c) {
    return new \Slim\Csrf\Guard;
};

// HTML form including fields for CSRF token
$app->get('/', function ($request, $response) {
    return $this->renderer->render($response, 'view.twig'); // Twig
    return $this->renderer->render($response, 'view.php'); // Or PHP
})->add(new CsrfTokenToView($container->csrf, $container->renderer))
    ->add($container->csrf);

// CSRF protected action, can be called by AJAX
$app->post('/submit', function ($request, $response) {
    if ($request->isXhr()) {
        return $response->withJson(['success' => true]);
    } else {
        return $response->withRedirect('/');
    }
})->add(new CsrfTokenToHeaders($container->csrf))
    ->add($container->csrf);

// Slim dispatching
$app->run();

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>CSRF</title>
    </head>
    <body>
        <form action="/submit" method="post">
             if (isset($csrf_token) and !empty($csrf_token)): 
apache_conf
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>