Skip to main content

CSRF lib

This guide provides documentation for the csrf class methods used in the AVRO framework to protect against Cross-Site Request Forgery (CSRF) attacks.


input_field()

Generate a hidden CSRF input field to be included in forms.
This method creates a token for a specific action and embeds it into the HTML form.

Parameters:
string $action_name

Usage Example (Frontend):

$this->lib->csrf->input_field('<my_action_name>');

Example Output:

<input type="hidden" name="_token" value="c7a4f9b2a4c0f3caa6bfa2e4dc2b71a7">

generate()

Manually generate a CSRF token for a given action.
This is automatically used by input_field(), but can also be called directly.

Parameters:
string $action_name

Usage Example:

$token = $this->lib->csrf->generate('user_login');
echo $token; // Prints generated token string

validate()

Validate the CSRF token received from a submitted form against the stored token.
If the validation fails, you should reject the request (for example, return 404 or show an error).

Parameters:
string $action_name, string $token, bool $destroy_after = true

  • $action_name — The name of the action that was protected
  • $token — The token received from the POST request
  • $destroy_after — If true, deletes the token after successful validation

Usage Example (Backend):

// CSRF protection 
$posted_token = $this->lib->filter->post('_token');
if (!$this->lib->csrf->validate('<my_action_name>', $posted_token, true)) {
$this->app->error_404($this->app->language('Security_token_mismatch'));
}

destroy()

Delete the token for a given action manually.

Parameters:
string $action_name

Usage Example:

$this->lib->csrf->destroy('user_login'); // Removes token for 'user_login' action

exists()

Check if a token for a given action exists in the session.

Parameters:
string $action_name

Usage Example:

$this->lib->csrf->exists('user_login'); // True or False

get()

Get the currently stored token for a specific action (if it exists).

Parameters:
string $action_name

Usage Example:

$token = $this->lib->csrf->get('user_login');
echo $token;

clear_all()

Clear all CSRF tokens from session storage.

Parameters:
None

Usage Example:

$this->lib->csrf->clear_all(); // Removes all CSRF tokens

⚙️ Notes

  • Always include $this->lib->csrf->input_field('<action>') in every form.
  • Always validate using $this->lib->csrf->validate('<action>', $posted_token, true) before processing POST data.
  • Tokens are session-based and must match the action they were generated for.

This ensures that only valid requests from your application's pages are accepted, protecting against CSRF attacks.