Joomla – How to set and get $_SESSION variables by an external PHP-script



When you are trying to set or get $_SESSION variable in Joomla environment using standart approach from an external script, it appears to be empty or not set.

$_SESSION['variable_name'] = "test";
$test_var = $_SESSION['variable_name']; // $test_var is empty!?!

It happens because Joomla uses its own session handling with come unique session-id-generation and some encryption in place, so the only way to get into the Joomla session data is to use the appropriate Joomla functions. I recently had a project where I needed to make simple data-input form with captcha generator and the original captcha data was stored in (and then got from) session.

So, if you want to put your data in session under Joomla, you should “connect” to the Joomla’s framevork first:

define( '_JEXEC', 1 );
define( 'JPATH_BASE', __DIR__);
require_once ( JPATH_BASE.'/includes/defines.php' );
require_once ( JPATH_BASE.'/includes/framework.php' );
$joomla_mainframe = JFactory::getApplication('site');
$joomla_mainframe->initialise();

Be sure to define JPATH_BASE to suit your directory structure accordingly to the location of your script. It can be just __DIR__ if your php-script is located in the “root” of Joomla site (where index.php is located).

Now we can set the variable in session:

$session = JFactory::getSession();
$session->set('session_variable_name', $variable_value);

To read the variable’s value from session, we need to “connect” to Joomla’s framework again (see above) and GET it from it:

... // Initializing of Joomla's framework
$session = JFactory::getSession();
$variable_value = $session->get('session_variable_name');
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>