简体   繁体   中英

Accessing session data outside Joomla

I am trying to run an application outside Joomla (not as a plugin) and I would like to access the logged in user's information (userid). I am wondering how should I go about doing that? Is there a file which I can include? I tried using $_SESSION but it shows empty.

Is there a simple solution to my problem? Thank you for your time.

Actually that's not as easy as it sounds. 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 (as others have suggested). I recently had a project where we needed to transfer a Joomla authenticated user into a separate application. We did this by adding a Joomla adapter which instantiates the Joomla user classes, reads the user data, puts everything into an encrypted cookie and redirects back to our application. In there we read the encrypted cookie, instantiate our own user object and discard the cookie. As this is not 100% secure we're changing the system to write the user data in a database table and read it from our application - we avoid the unsecure way through a cookie that way, because even though the cookie is encrypted (and contains sensitive user information which suffice to authenticate a user) it'll be transfered on wire and could be sniffed.

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(dirname(__FILE__)));
define( 'DS', DIRECTORY_SEPARATOR );

require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');

$mainframe = JFactory::getApplication('site');

The above is the basic script required to access Joomla resources.

 define( '_JEXEC', 1 );

 define('JPATH_BASE', 'your joomla basedir goes here' );

 define( 'DS', DIRECTORY_SEPARATOR );
 require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
 require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

 JDEBUG ? $_PROFILER->mark( 'afterLoad' ) : null;
 $mainframe =& JFactory::getApplication('site');
 $mainframe->initialise();
 JPluginHelper::importPlugin('system');
 JDEBUG ? $_PROFILER->mark('afterInitialise') : null;
 $mainframe->triggerEvent('onAfterInitialise');

 $user =& JFactory::getUser();

    if ($user->guest) {
        echo 'stuff';
            //redirect('/');
    } else {
        echo 'user';
    }

The solution is to set the session for your whole domain and/or site. It applies if you're trying to access the session data outside of joomla scope. For example, if your joomla site is located on http://example.com/joomla/ and your other site on http://othersite.example.com/ then the cookie holding the session id is not transmitted from joomla to the other site. To modify this behaviour, use session_ set_ cookie_ params (I don't know joomla very well, but you should have to add only a few lines of code).使用 session_ set_ cookie_ params (我不太了解 joomla,但您应该只需要添加几行代码)。 Use it this way:

session_set_cookie_params(86400, '/', '.example.com');

86400 is the lifetime of the session, set it to what you prefer (86400 is one day). '/' is the path of the cookie. It means that if your joomla site is located on http://example.com/joomla/ , the session cookie will still be sent if the user accesses http://example.com/ .

'.example.com' is the domain. Note the dot at the beginning, it's very important. It says that the session cookie will be sent on any subdomain of example.com. If you don't put it, the cookie will be sent only for addresses starting with http://example.com/ .

This should solve your problem, unless you are trying to access the session data from another domain. If it's the case, leave a comment here, I'll see if I cand find something.

First of all you have to provide definition to some joomla's constants(identifiers) as follows:

define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE',$_SERVER['DOCUMENT_ROOT'].DS. basename(dirname(__DIR__)) );

where: JPATH_BASE is represents your site's root directory. It must be correct.

After than, you have to use key files as follows:

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

After than, you have to create an application object and initialize it also:

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();  

[this is optional] If you want to import some other libraries, then you can do this as follows:

jimport( 'joomla.user.user');
jimport( 'joomla.session.session');
jimport( 'joomla.user.authentication');

So the core code for your file is as follows:

define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE',$_SERVER['DOCUMENT_ROOT'].DS. basename(dirname(__DIR__)) );

require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

//optional use depend on requirement 
jimport( 'joomla.user.user');
jimport( 'joomla.session.session');
jimport( 'joomla.user.authentication');

The solution showed by Stefan Gehrig

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(dirname(__FILE__)));
define( 'DS', DIRECTORY_SEPARATOR );

require_once (JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once (JPATH_BASE . DS . 'includes' . DS . 'framework.php');

$mainframe = JFactory::getApplication('site');

works fine, I have spent many long nights trying access the Joomla! resources outside the joomla folder.

$session     = &JFactory::getSession();

In the follow up code, works fine when the getApplication method has been invoked.

Thanks for solution.

to get the user id you need to use Joomlas functions:

$user =& JFactory::getUser();
$user->get('id');

will let you get the user ID. you will however need to do this inside of the joomla page so i dont know how usefult hat will be to you.

apply this in mod_login.php

After: $user =& JFactory::getUser();

echo "<p>Your usertype is {$user->usertype} which has a group id of {$user->gid}.</p>";

It is very possible that like Wordpress, Joomla doesn't use any 'session' data, but rather pulls data directly from the database. In which case you would need to use Joomla's native functions.

But that is just from my experience with Wordpress.

Updated

I guess I was wrong.
Supposidly this is the api class for accessing Joomla Session variables:

// Returns a reference to the global JSession object, only creating it if it doesn't already exist $session = &JFactory::getSession();

// Get a value from a session var $value = $session->get('var_name', null);

// Put a value in a session var $session->set('var_name', $value);

It might be helpful to see how such is achieved in application bridges like jFusion. I suggest at least a system plugin for Joomla, that will use joomla functions to get everything you need from the joomla install and shipto your application onApplicationInitialize. The most important issue will be ur data flow modelling!

I put below code in Joomla index.php and it's work fine for me.

//Set session to access it outside
$user =& JFactory::getUser();
$username = $user->get('username');

session_start();
$_SESSION['username'] = $username;

Now you can use session variable outside Joomla as below

session_start();
$_SESSION['username'];

I cannot tell you how Joomla with versions above 1.5 does that but in Joomla 1.5 here is how you do that: ( I am sure for other versions procedure is very similar )

Joomla generates Unique session id for front-end of the website and back-end. To access session data all you need is know the session id.

In joomla configuration file there is a parameter called " secret "

For back-end this is how you generate session id:

$session_id = md5( md5( JConfig::$secret.'administrator' ) );

and for front end:

$session_id = md5( md5( JConfig::$secret.'site' ) );

After this a simple query

mysql_query( 'SELECT `data` FROM jos_session WHERE session_id="'.$sessionId.'"  )

will give you access to session data. All you need is to decrypt it with session_decode and session data will be in $_SESSION variable.

Don't forget to put session_start before session_decode otherwise it will not work

To get Joomla user id use:

$user =& JFactory::getUser();
$user_id = $user->get('id');

and to get user session id use:

$session = & JFactory::getSession();
$session_id = $session->getId();

If you store your sessions in database, you could decode session data as in this comment:

http://www.php.net/manual/en/function.session-decode.php#79244

A solution for Joomla 3, without using any libraries.

require_once '../configuration.php'; // load Joomla configuration file
$jConfig = new \JConfig();
$secret = $jConfig->secret;
$dbprefix = $jConfig->dbprefix;
$cookieName = md5(md5($secret . 'site'));
$sessionId = $_COOKIE[$cookieName];
$sql = "select userid from {$dbprefix}session where client_id = 0 and session_id = ?";
$userId = $db->lookup($sql, [$sessionId]);

(The code above is simplified, without any error handling.)

I assume that by application you mean another website. Your best bet is to have an iframe in that application instantiating the Joomla startup file, get the user id in that iframe, store it somewhere in the database along with your current session id, and then retrieve it by the other application. Will take some time though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM