1

How we can get the logged in user information and session information from external php script with Joomla-4.x?

The below code working with Joomla 3.x and doesn't working with Joomla-4.x

define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../..' ));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
$session = JFactory::getSession();
jimport( 'joomla.application.module.helper' );
 
$session = $session->getId();
$db = JFactory::getDbo();
$user =& JFactory::getUser();
$userid= $user->id;
1
  • Welcome to JSE. Please take our tour while you wait for support. How close does this answer get you? joomla.stackexchange.com/a/31503/12352 Whenever "something doesn't work", please do your best to specify how it doesn't work. Including error messages and actual output when things go wrong is an important inclusion in a complete question. Commented Sep 19, 2021 at 5:21

1 Answer 1

1

The below code is mostly from Joomla's /includes/app.php but without the last line. The last few lines then get information about the user and the user session.

<?php
define('_JEXEC', 1);
define('JPATH_BASE', __DIR__);
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';

// Boot the DI container
$container = \Joomla\CMS\Factory::getContainer();

/*
 * Alias the session service keys to the web session service as that is the primary session backend for this application
 *
 * In addition to aliasing "common" service keys, we also create aliases for the PHP classes to ensure autowiring objects
 * is supported.  This includes aliases for aliased class names, and the keys for aliased class names should be considered
 * deprecated to be removed when the class name alias is removed as well.
 */
$container->alias('session.web', 'session.web.site')
    ->alias('session', 'session.web.site')
    ->alias('JSession', 'session.web.site')
    ->alias(\Joomla\CMS\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');

// Instantiate the application.
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);

// Set the application as global app
\Joomla\CMS\Factory::$application = $app;

$userInfo = \Joomla\CMS\Factory::getApplication()->getSession()->get('user');
$userSession = \Joomla\CMS\Factory::getApplication()->getSession();

Disclaimer: Most of the information in this post was derived from https://gist.github.com/PhilETaylor/0c36d87da0f2ad231b378b47c54cfb9b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.