PHP code example of spencer14420 / sp-anti-csrf

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

    

spencer14420 / sp-anti-csrf example snippets


use spencer14420\SpAntiCsrf\AntiCsrf;

$csrf = new AntiCsrf();
$token = $csrf->generateToken();

use spencer14420\SpAntiCsrf\AntiCsrf;

$csrf = new AntiCsrf();

try {
    $token = $_POST['csrf_token'] ?? '';
    if (!$csrf->tokenIsValid($token)) {
        throw new Exception('Invalid CSRF token.');
    }
    // Proceed with processing the form
} catch (Exception $e) {
    // Handle invalid or expired token
    echo 'Error: ' . $e->getMessage();
}

$csrf->regenerateSession();

generateToken(int $expirySeconds = 3600): string

tokenIsValid(string $tokenToCheck): bool

regenerateSession(): void

tokenIsNotExpired(): bool
html
<input
  type="hidden"
  id="csrf_token"
  name="csrf_token"
  value=" echo $token