Joomla has a built in functionality to make it easy for developers to store and retrieve variables that are stored with the session. There are two ways to set user state variables.

Method 1: JApplication::setUserState

$mainframe =JFactory::getApplication();

// store the variable that we would like to keep for next time
// function syntax is setUserState( $key, $value );
$mainframe->setUserState( "$option.state_variable", "state1" );

The first parameter is the key under which to store the variable. The $option variable is extension-specific prefix and avoids extensions interfering with each other. The second parameter is the value to store with the state variable.

Method 2: JApplication::getUserStateFromRequest

$mainframe =JFactory::getApplication();

// retrieve the value of the state variable. First see if the variable has been passed
// in the request. Otherwise retrieve the stored value. If none of these are specified,
// the specified default value will be returned
// function syntax is getUserStateFromRequest( $key, $request, $default );
$stateVar = $mainframe->getUserStateFromRequest( "$option.state_variable", 'state_variable', 'state1' );

This method will update the user state variable by looking in the variables that were passed with the request (in either GET or POST) and updating the user state variable if the specified request variable is set. This can be used to set user state variables with values that are passed from forms. If an existing value can be found either in the request or in the stored state variable, this is returned. Otherwise, the specified default value is returned (if it is specified), or NULL is returned if no value can be found.

Method 3: JApplication::getUserState

$mainframe =JFactory::getApplication();

// retrieve the value of the state variable. If no value is specified,
// the specified default value will be returned.
// function syntax is getUserState( $key, $default );
$stateVar = $mainframe->getUserState( "$option.state_variable", 'state1' );

This method will retrieve the value of the specified user state variable. If this user state variable has not been set, then the value is read from the $default parameter. If the user state variable has not been set and $default is not specified, the method will return NULL.