Joomla is a powerful content management system for many reasons. Here is one quick article about how to use a custom session variable in Joomla.Today I have setup custom session variable in Joomla So I thought it would be good to share how to get and set session variables in Joomla.
Joomla uses own session management so if you use PHP session with Joomla there is no guarantee that it works properly. To get values use Joomla session management with using a the session handling code.Joomla session uses a class JSession with which we can work with sessions in the Joomla framework.
How to set a session variable:
The below code gets the current session and sets the value of the session variable ‘Sess_var’ to ‘yes’.
$session = &JFactory::getSession(); // To get the session object $session->set( 'Sess_var', 'yes' ); // To get a session variable
To assign the value in Joomla using the session, $session as a reference to an object for the current session.Using $session, you can set the session and in that first is the name of the variable and the second parameter is the value of the variable.
How to get a session variable:
After setting session, To retrieve session variable,
$session = &JFactory::getSession(); $session_val = $session->get( 'Sess_var'); // To set or retrieve a session variable
Here, I have used JFactory reference variable with function getSession and assign it to variable $session.Next, You can use that variable to retrieve the specific session variable.
How to unset a session variable:
If you get and set the session in Joomla, You might want to clear the session or remove the session variable. Use below code to unset session variable after using it,
$session->clear('Sess_var'); //To unset or clear session variable
Hopefully this article will help someone. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates. Do you have any question about Joomla Session or any issue in using any variable? Let me know in comment section.