Using JSessions

  • PDF

Joomla Class Notes - Session information

Sessions are useful for preventing form hijacking, hackers may try to input injected code to forms. By using a session variable you can confirm that the form data was sent from a user with a valid session id preventing hacker from hijacking your forms.

So assuming we are creating a form and then passing the form information to some handling code we'll want to add the following:

// In the form echo the session token

echo JHTML::_('form.token');

// When processing the form first check the token; if invalid exit (using jexit();)

// make sure the token is valid

JRequest::checkToken() or jexit('Invalid Token');

That is all there is to making sure you are processing a valid form from a valid user.

An example of this method of using sessions with the JRequest::checkToken() function is presented here, scroll down to "Extending and editing user parameters":

Another example of how to use JSession, for preventing saving duplicate row, is provided here:

The Joomla! documentation is located here:

Another alternative is to send the session token in the form variables and then check on the receiving end:

 $session =& JFactory::getSession(); 
If( JRequest::getVar('token') != $session->getToken()) jexit('Unauthorized User - Invalid Token');

In class use our simple guestbook component* and add the following:

  1. Create a session in the form and submit the token for that session.
  2. In the function that process the form - check the form sent a valid token. If the token is vaild process the form, if the token is invalid display an error message.

To test for an invalid session, set the session time out to a minute (in the Global Configuration -> System settings) fill in the form and wait a minute, then submit the form.  The result should be an invalid form.

*From our textbook - Professional Joomla!, by Dan Rahmel