CSRF (Cross-Site Request Forgery)

The CSRF class provides protection against Cross-Site Request Forgery attacks by generating and validating tokens. It automatically manages tokens within the user's session.

Constructor

__construct
__construct(array $config = []): CSRF

Creates a new CSRF instance with optional configuration.

Parameters

NameTypeRequiredDescription
$config array No Configuration options for CSRF behavior

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();

Methods

token
token(): string

Generates a new CSRF token and stores it in the session.

Returns

A unique CSRF token string.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$token = $csrf->token();
// Use $token in a hidden form field or meta tag
verify
verify(string $token): bool

Verifies a CSRF token. The token is consumed upon successful verification.

Parameters

NameTypeRequiredDescription
$token string Yes The token to verify

Returns

true if the token is valid, false otherwise.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$token = $_POST['_token'] ?? '';
$isValid = $csrf->verify($token);

if ($isValid) {
    // Process form
} else {
    // Handle invalid token
}
verifyAndKeep
verifyAndKeep(string $token): bool

Verifies a CSRF token without consuming it. This is useful for AJAX-heavy applications where the same token might be used for multiple requests.

Parameters

NameTypeRequiredDescription
$token string Yes The token to verify

Returns

true if the token is valid, false otherwise.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
$isValid = $csrf->verifyAndKeep($token);

if ($isValid) {
    // Process AJAX request
}
getTokenFromRequest
getTokenFromRequest(): ?string

Retrieves the CSRF token from the current request ($_POST, $_GET, or headers).

Returns

The token string if found, otherwise null.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$token = $csrf->getTokenFromRequest();
validateRequest
validateRequest(): bool

Validates the CSRF token from the current request. This is a convenience method that combines getTokenFromRequest() and verify().

Returns

true if the request is valid, false otherwise.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
if ($csrf->validateRequest()) {
    // Request is valid
}
generateField
generateField(): string

Generates an HTML hidden input field containing a new CSRF token.

Returns

An HTML string.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
echo $csrf->generateField();
// Output: 
generateMetaTag
generateMetaTag(): string

Generates an HTML meta tag containing a new CSRF token, useful for JavaScript-based requests.

Returns

An HTML string.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
echo $csrf->generateMetaTag();
// Output: 
clearTokens
clearTokens(): void

Removes all CSRF tokens from the session.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$csrf->clearTokens();
getActiveTokenCount
getActiveTokenCount(): int

Returns the number of active (non-expired) CSRF tokens in the session.

Returns

An integer representing the token count.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();
$count = $csrf->getActiveTokenCount();
requireValidFromGlobals
requireValidFromGlobals(): void

A strict method that checks for a valid token from superglobals and throws a RuntimeException if the token is missing or invalid.

Throws

RuntimeException on failure.

Example

$config = [
    'db' => [
        'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
        'user' => 'your_username',
        'pass' => 'your_password'
    ],
    'storage_path' => __DIR__ . '/storage'
];

$schoolKit = SchoolKit::start($config);
$csrf = $schoolKit->csrf();

try {
    $csrf->requireValidFromGlobals();
    // Proceed with action
} catch (RuntimeException $e) {
    // Halt execution or show an error
    http_response_code(403);
    echo "Invalid CSRF token.";
}