PHP Joomla! 6 Joomla! 5 Joomla! 3 (Legacy) Component Basic

Protect Forms and AJAX Endpoints Against CSRF with Session::checkToken()

Renders HTMLHelper::_('form.token') in forms and verifies the session token inside controllers with Session::checkToken().

Updated on 24 November 2026 56 copies 189 views
components/com_example/src/Controller/ActionController.php
<?php

declare(strict_types=1);

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Session\Session;

// 1) No formulário HTML:
// echo HTMLHelper::_('form.token');

// 2) No Controller (POST ou GET):
if (!Session::checkToken('post')) {
    throw new \RuntimeException(Text::_('JINVALID_TOKEN'), 403);
}
For JSON endpoints, respond with HTTP 403 and a JsonResponse on invalid tokens.
components/com_example/src/Controller/ActionController.php
<?php
// No form: echo JHtml::_('form.token');
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
Legacy Joomla 3 version using JSession::checkToken() and JHtml.

Technical explanation and best practices

Every state-changing endpoint (POST forms, AJAX votes, deletes or updates) must validate the Joomla CSRF session token using Session::checkToken() or $this->checkToken().

Direct Engineering

Have a Joomla project or technical challenge in mind?

From architectural diagnosis to production deployment, directly with the engineer.