PHP code example of kylekatarnls / csrfprotect

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

    

kylekatarnls / csrfprotect example snippets




use \CsrfProtect\CsrfProtect as Csrf;

session_start();

if (isset($_POST['message'])) {
    if (Csrf::checkToken()) {
        echo 'Thanks for your message!';
    } else {
        echo 'Sorry, your session expired.';
    }
}




use \CsrfProtect\CsrfProtect as Csrf;

session_start();

if (isset($_POST['message'])) {
    if (Csrf::checkPostToken($_SESSION['user_id'])) {
        echo 'Thanks for your message!';
    } else {
        echo 'Sorry, your session expired or you have log out.';
    }
}




use \CsrfProtect\CsrfProtect as Csrf;

session_start();

if (isset($_POST['message'])) {
    if (Csrf::checkToken($_GET['_csrf'])) {
        echo 'Thanks for clicking!';
    } else {
        echo 'Sorry, your session expired.';
    }
}




use \CsrfProtect\CsrfProtect as Csrf;

if (isset($_POST['message'])) {
    if (Csrf::checkToken($_GET['_csrf'], $_SESSION['user_id'])) {
        echo 'Thanks for clicking!';
    } else {
        echo 'Sorry, your session expired.';
    }
}




class ShortCsrf extends \CsrfProtect\CsrfProtect
{
    const TOKEN_LENGTH = 6;
}

class LongCsrf extends \CsrfProtect\CsrfProtect
{
    const TOKEN_LENGTH = 64;
}

echo ShortCsrf::getTag(); // Display an hidden input tag with a 6 chars token
echo LongCsrf::getTag(); // Display an hidden input tag with a 64 chars token




class Csrf extends \CsrfProtect\CsrfProtect
{
    const POST_KEY = "_csrf";
    const SESSION_PREFIX = "_csrf_";
    const TOKEN_LENGTH = 32;
    const TOKEN_CHARS = "azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890_-";
    const TOKENS_LIMIT = 5000;
}




class Csrf extends \CsrfProtect\CsrfProtect
{
    public static function getTag($identifier = "")
    {
        return str_replace('>', ' />', parent::getTag($identifier));
    }
}




session_start();

if (isset($_POST['message'])) {
    if (\CsrfProtect\checkToken()) {
        echo 'Thanks for your message!';
    } else {
        echo 'Sorry, your session expired.';
    }
}