PHP code example of joefallon / phpcsrf

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

    

joefallon / phpcsrf example snippets


use JoeFallon\PhpSession\Session;
use JoeFallon\PhpCsrf\CsrfGuard;

$session = new Session();
$guard = new CsrfGuard('contact_form', $session);

$token = $guard->generateToken();
// Print in a hidden input (escape for HTML)
echo "<input type=\"hidden\" name=\"csrf_token\" value=\"" .
      htmlspecialchars($token, ENT_QUOTES | ENT_HTML5) . "\" />";

$submitted = $_POST['csrf_token'] ?? '';
try {
    if ($guard->isValidToken((string)$submitted)) {
        // Token valid — process the form
    } else {
        // Token invalid — reject the request
        http_response_code(403);
        echo 'Invalid CSRF token.';
    }
} catch (InvalidArgumentException $e) {
    // Token was empty or invalid input
    http_response_code(400);
    echo 'Bad request.';
} catch (RuntimeException $e) {
    // Failure generating secure randomness (rare) — treat as server error
    http_response_code(500);
    echo 'Server error.';
}

// token-endpoint.php
$session = new \JoeFallon\PhpSession\Session();
$guard = new \JoeFallon\PhpCsrf\CsrfGuard('ajax_form', $session);
$token = $guard->generateToken();
header('Content-Type: application/json');
echo json_encode(['csrf_token' => $token]);

session_set_cookie_params([
    'secure' => true,      // send only over HTTPS
    'httponly' => true,    // deny access from JavaScript (mitigates XSS token theft)
    'samesite' => 'Lax',   // consider 'Strict' if appropriate for your UX
]);
session_start();