API reference
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(): intsetTokenLength(int $newTokenLength): voidgenerateNewToken(): stringverify(array|object $postData): voidsaveToken(string $token): voidconsumeToken(string $token): voidverifyToken(string $token): void
GT\Csrf\ArrayTokenStore
In-memory implementation of TokenStore.
Methods
- inherits the constructor from
TokenStore saveToken(string $token): voidconsumeToken(string $token): voidverifyToken(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): voidconsumeToken(string $token): voidverifyToken(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): stringgetHTMLDocument(): 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/domforGT\Dom\HTMLDocumentphpgt/sessionfor the built-in session-backed token store