14

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.

Alec Smart
  • 94,115
  • 39
  • 120
  • 184

15 Answers15

19

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.

Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
  • I'd like to pull this kind of functionality into CakePHP. The cake-based site is hosted on a subdomain. Do you think your advice would apply to my problem? – Randy L Apr 12 '10 at 23:40
  • I do not know CakePHP and its authentication mechanisms but I think this approach could work in general - as long as you're able to transfer an identifier (a cookie in my case) from application 1 to application 2. Given a subdomain it should be no problem to have a cookie that can be read from the subdomain as well as from the main domain. – Stefan Gehrig Apr 13 '10 at 06:54
  • Sorry for the noob question, but I am assuming we put this in a PHP script, in the base Joomla directory? – Jaryl May 27 '10 at 04:07
  • @Jaryl: You have to put this in a PHP script - that's correct. The location of this script doesn't matter as long as you adjust the `JPATH_BASE` constant to the path where your Joomla installation can be found. – Stefan Gehrig May 27 '10 at 06:50
8
 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';
    }
Maurizio Pozzobon
  • 3,044
  • 7
  • 34
  • 44
jkatzer
  • 724
  • 7
  • 12
4

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 before every session_start() (I don't know joomla very well, but you should have to add only a few lines of code). 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.

FWH
  • 3,205
  • 1
  • 22
  • 17
2

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');
2

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.

Adam
  • 43,763
  • 16
  • 104
  • 144
Carlos Spohr
  • 507
  • 11
  • 24
1

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.

schubySteve
  • 707
  • 1
  • 4
  • 9
  • This is what I did. I couldn't work out what the minimal environment I needed to set up to get access to Joomla functions, so I just bit the bullet and learnt how to write components. They're a bit weird, but not so bad once you get the hang of it. Then at least, you can pretty much get whatever you want via the Joomla API. – nedned Nov 14 '09 at 06:11
1

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>";

GDP
  • 8,109
  • 6
  • 45
  • 82
rishabh
  • 11
  • 1
0

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);

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
0

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!

stone
  • 2,192
  • 16
  • 26
0

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'];

0

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

0

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();
Miro
  • 1
0

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

GDR
  • 2,301
  • 1
  • 21
  • 26
0

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.)

Christian d'Heureuse
  • 5,090
  • 1
  • 32
  • 28
0

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.

itoctopus
  • 4,133
  • 4
  • 32
  • 44