PHP code example of ocramius / psr7-csrf

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

    

ocramius / psr7-csrf example snippets


$app = \Zend\Expressive\AppFactory::create();

$app->pipe(\PSR7Session\Http\SessionMiddleware::fromSymmetricKeyDefaults(
    'mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw=', // replace this with a key of your own (see PSR7Session docs)
    1200 // 20 minutes session duration
));

$app->pipe(\PSR7Csrf\Factory::createDefaultCSRFCheckerMiddleware());

$tokenGenerator = \PSR7Csrf\Factory::createDefaultTokenGenerator();

$app->get('/get', function ($request, $response) use ($tokenGenerator) {
    $response
        ->getBody()
        ->write(
            '<form method="post" action="/post">'
            . '<input type="submit"/>'
            . '<input type="hidden" name="csrf_token" value="'
            . $tokenGenerator($request)
            . '"/>'
            . '</form>'
        );

    return $response;
});

$app->post('/post', function ($request, $response) {
    $response
        ->getBody()
        ->write('It works!');

    return $response;
});