PHP code example of lithemod / csrf

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

    

lithemod / csrf example snippets


use Lithe\Middleware\Security\csrf;

$app->use(csrf([ 
    'expire' => 600, // Token expiration time in seconds
]));

$app->use(csrf([ 
    'name' => '_csrf_token', 
    'expire' => 900, // 15 minutes 
    'checkBody' => true, 
    'bodyMethods' => ['POST', 'PUT', 'DELETE'], 
    'regenerate' => true,
]));

$app->get('/generate-token', function ($req, $res) {
    $token = $req->csrf->generateToken();
    return $res->json(['token' => $token]);
});

$app->get('/get-token', function ($req, $res) {
    $token = $req->csrf->getToken();
    return $res->json(['token' => $token]);
});

$app->get('/form', function ($req, $res) {
    $tokenField = $req->csrf->getTokenField();
    return $res->send("
        <form method='POST' action='/submit'>
            $tokenField
            <input type='text' name='data' 

$app->post('/submit', function ($req, $res) {
    $token = $req->input('_csrf_token'); // Change to the token name if necessary
    if ($req->csrf->verifyToken($token)) {
        // Process the request
        return $res->json(['message' => 'Data submitted successfully!']);
    } else {
        // Handle the invalid token
        return $res->status(419)->json(['error' => 'Invalid CSRF token!']);
    }
});

$app->post('/invalidate-token', function ($req, $res) {
    $req->csrf->invalidate();
    return $res->json(['message' => 'CSRF token invalidated!']);
});

$app->get('/check-token', function ($req, $res) {
    $exists = $req->csrf->exists();
    return $res->json(['token_exists' => $exists]);
});