get joomla4 login in external php script

85 views
Skip to first unread message

Emmanuel Ingelaere

unread,
Nov 17, 2021, 3:32:33 AM11/17/21
to Joomla! General Development
Hi everybody,

I'm writing a php database app in which I want to use joomla4 as login system. I think I remember using the following method succesfully in the past to check if a user is logged on:
--------------------
define( '_JEXEC', 1 );
define( '_VALID_MOS', 1 );
define('JPATH_BASE', dirname(__FILE__));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
//JPluginHelper::importPlugin('system');
//$mainframe->triggerEvent('onAfterInitialise');

$user = JFactory::getUser();
------------------------
I got this from following post:

Does someone know how to achieve this in Joomla4? The above code throws an error in the line: $user = JFactory::getUser();

Any tips on doing this by the book are also very welcome!

Emmanuel Ingelaere

unread,
Nov 17, 2021, 3:36:06 AM11/17/21
to Joomla! General Development
The error thrown is " Failed to start application "

Op woensdag 17 november 2021 om 09:32:33 UTC+1 schreef Emmanuel Ingelaere:

Elvis

unread,
Nov 17, 2021, 7:44:27 AM11/17/21
to Joomla! General Development
Hi!

You are using old code, it won't work in J4, try this

<?php

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
 
if (file_exists(dirname(__FILE__) . '/defines.php')) {
 include_once dirname(__FILE__) . '/defines.php';
}
 
if (!defined('_JDEFINES')) {
 define('JPATH_BASE', 'PATH_TO_YOUR_JOOMLA_SITE_ROOT_FOLDER');
 require_once JPATH_BASE.'/includes/defines.php';
}
 
require_once JPATH_BASE.'/includes/framework.php';

I didn't test it in J4, but it should work

Alex Chartier

unread,
Nov 17, 2021, 7:55:04 AM11/17/21
to Joomla! General Development
I have run into this myself and created a wrapper which will work on both J3 & J4. It does not actually log the user in but you could do that yourself. Please see the attached file.
ApplicationWrapper.php

Alex Chartier

unread,
Nov 17, 2021, 7:56:42 AM11/17/21
to Joomla! General Development
p.s. I should have sanitized it a bit. Remove the function and call for bootJmailqPlugin (unless you are running JmailQ which you probably are not).

Emmanuel Ingelaere

unread,
Nov 17, 2021, 9:57:19 AM11/17/21
to joomla-de...@googlegroups.com
Hi!

Thanks to both of you for the quick response! Both your suggested code works without errors.

However, in both cases, querying and displaying the user object results in an empty object, even when a user is logged in.

To test this I used the following setup:

-installed a joomla 4.0 testsite
-login in this testsite with a random user
-in a separate tab of firefox, run the php-script with your code (made one version for each of you), followed by: $user = JFactory::getUser(); print_r($user);
-this script sits in the root of the site
-the print_r gives following result in both cases:

Joomla\CMS\User\User Object ( [isRoot:protected] => [id] => 0 [name] => [username] => [email] => [password] => [password_clear] => [block] => [sendEmail] => 0 [registerDate] => [lastvisitDate] => [activation] => [params] => [groups] => Array ( ) [guest] => 1 [lastResetTime] => [resetCount] => [requireReset] => [_params:protected] => Joomla\Registry\Registry Object ( [data:protected] => stdClass Object ( ) [initialized:protected] => [separator] => . ) [_authGroups:protected] => [_authLevels:protected] => [_authActions:protected] => [_errorMsg:protected] => [userHelper:protected] => Joomla\CMS\User\UserWrapper Object ( ) [_errors:protected] => Array ( ) [aid] => 0 )

Am I missing something or doing something wrong? Thx!


Op wo 17 nov. 2021 om 13:56 schreef Alex Chartier <al...@thealgonquinclub.com>:
--
You received this message because you are subscribed to the Google Groups "Joomla! General Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to joomla-dev-gene...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/joomla-dev-general/c356ab28-bc6d-4bb5-9eb2-32aa64155e8en%40googlegroups.com.

Alex Chartier

unread,
Nov 17, 2021, 10:10:02 AM11/17/21
to Joomla! General Development
Two things. First you have not logged in, and second you have not provided a userID for the getUser. When calling the getUser as you have, without a user ID, Joomla will return a user object of the currently logged in user. Since no user is logged in you are getting an empty object. To log in the user take a look here: https://stackoverflow.com/questions/2075335/how-to-log-into-joomla-through-an-external-script

If you are using my script, you will want to place this in the doExecute function of your class. Once logged in the getUser will return the user object of that user.

Emmanuel Ingelaere

unread,
Nov 22, 2021, 11:21:40 AM11/22/21
to joomla-de...@googlegroups.com
Ok, thx, it works now! Thanks a lot for pointing me in the right direction. For others facing the same question, here's the complete solution I used:

error_reporting(E_ALL);
ini_set('display_errors', 1);

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;

After this you can login with:

$result_login = JFactory::getApplication()->login(
    [
        'username' => 'user01',
        'password' => 'secret'
    ],
    [
        'remember' => true,
        'silent'   => true
    ]
);

Or check if a user is already logged in or get the session info using:

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

var_dump($userInfo);
echo "<p>-</p>";
var_dump($userSession);


From a security point of view when you check if the user is already logged on:
-suppose a user installs his own joomla-site and on both sites the user 'admin' exists...
-An external script checking if the user is logged on, could be fooled in believing the user is logged on as admin? Or am I wrong? So how to check if the user is coming from the correct joomla-site?


Op wo 17 nov. 2021 om 16:10 schreef Alex Chartier <al...@thealgonquinclub.com>:
Reply all
Reply to author
Forward
0 new messages