Skip to content

API reference

Greg Bowler edited this page Apr 22, 2026 · 1 revision

This page summarises the public API in phpgt/csrf.

Namespaces

The package now uses the GT\Csrf namespace prefix.

For backwards compatibility, Composer autoloading in this repository also accepts the legacy Gt\Csrf prefix.

GT\Csrf\TokenStore

Abstract base class for token generation and verification flow.

Generated tokens are returned as prefixed ULIDs beginning with CSRF_. The configured token length refers to the ULID portion only, so the full string length is the configured length plus the prefix length.

Methods

  • __construct(?int $maxTokens = null)
  • getMaxTokens(): int
  • setTokenLength(int $newTokenLength): void
  • generateNewToken(): string
  • verify(array|object $postData): void
  • saveToken(string $token): void
  • consumeToken(string $token): void
  • verifyToken(string $token): void

GT\Csrf\ArrayTokenStore

In-memory implementation of TokenStore.

Methods

  • inherits the constructor from TokenStore
  • saveToken(string $token): void
  • consumeToken(string $token): void
  • verifyToken(string $token): void

GT\Csrf\SessionTokenStore

Session-backed implementation of TokenStore.

Constants

  • SESSION_KEY = "tokenList"

Methods

  • __construct(Gt\Session\SessionContainer $session, ?int $maxTokens = null)
  • saveToken(string $token): void
  • consumeToken(string $token): void
  • verifyToken(string $token): void

GT\Csrf\HTMLDocumentProtector

Injects tokens into HTML documents.

Constants

  • ONE_TOKEN_PER_PAGE = "PAGE"
  • ONE_TOKEN_PER_FORM = "FORM"
  • TOKEN_NAME = "csrf-token"

Methods

  • __construct(string|GT\Dom\HTMLDocument $document, TokenStore $tokenStore)
  • protect(string $tokenSharing = self::ONE_TOKEN_PER_PAGE): string
  • getHTMLDocument(): GT\Dom\HTMLDocument

Exceptions

GT\Csrf\Exception\CsrfException

Base exception for all CSRF verification failures.

GT\Csrf\Exception\CsrfTokenMissingException

Thrown when submitted data contains no CSRF token.

GT\Csrf\Exception\CsrfTokenInvalidException

Thrown when the submitted token does not exist in the store.

GT\Csrf\Exception\CsrfTokenSpentException

Thrown when the submitted token exists but has already been used.

Dependencies

This package depends on:

  • phpgt/dom for GT\Dom\HTMLDocument
  • phpgt/session for the built-in session-backed token store