Thursday, 05 November 2015 08:21

Using Joomla Session and User Login in an External Script

Lets presume you need to use Joomla's session and user login (in this simple case) for your external scripts. This means that you don't want, don't know or don't need to build Joomla extension which is, if built and installed properly, inheriting all that Joomla offers. In our case, we just want script or scripts that are placed within folder under Joomla's root folder. Folder might be placed anywhere, of course, but you need to pay attention to locations afterwards.

So, create folder "myapp" under Joomla's root. Within that folder create folder "include". This might be place where you want to put all scripts that you need to include later on. One of them should be, for example, jsession.php. This script will contain following code:

// Get Joomla session
define( '_JEXEC', 1 );
define( 'DS', '/' );
// IMPORTANT: adjust path based on folder or define it manually as string 
// "myjoomlaroot" is name of your Joomla root folder
define( 'JPATH_BASE', $_SERVER['DOCUMENT_ROOT'] . "myjoomlaroot" );
require_once ( JPATH_BASE .DS. 'includes' .DS. 'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe = JFactory::getApplication('site');
jimport( 'joomla.user.user');
jimport( 'joomla.session.session');
jimport( 'joomla.user.authentication');
// now get user object and 3 example user variables
$user = JFactory::getUser(); 
$jid = $user->id; 
$jname = $user->name; 
$jguest = $user->guest;


Now you can create script within "myapp" folder. Let's call it myscript.php. There you need to include jsession.php script and then do whatever you wish with variables you get from Joomla. Let's presume you want to check if user is logged in and show content of page only to your Joomla registered users.



//including Joomla session and variables

//do we have logged in user or no
if (!$jid) {
	die("NO ACCESS! You need to login first");
else { 
      // some code that executes if user is logged in, i.e. show page and content


 If you're running site on your localhost server, you will access scripts we mentioned above this way then (use propper url, anyway):

http://localhost/myjoomlaroot (Joomla website where you need to login)


myscript.php script executes it's ELSE part if user is logged, otherways it dies with message "NO ACCESS! You need to login first". You can think of your own usage now, feel free to include all Joomla's resources, i.e almost all parts of it's powerfull framework this way. This was just small illustration of it.

Read 4237 times Last modified on Tuesday, 27 September 2016 11:55
Login to post comments