简体   繁体   中英

Joomla 4 user login programmatically

In the Joomla 3x, I have this code to login an user, it worked well.

$options = array();
$credentials = array();

$credentials['username'] = $username;
$credentials['password'] = $password;

$result = JFactory::getApplication()->login($credentials, $options);        
$result = ($result) ? 1 : 0;

echo json_encode( array('loggedIn' => $result) );
jexit();

But in the Joomla 4.2 it says error.

error

How to solve it? thanks!

I found this code, it's worked with Joomla 4.

$options = array();
$credentials = array();

$credentials['username'] = $username;
$credentials['password'] = $password;

$container = \Joomla\CMS\Factory::getContainer();
$container->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);
$result = $app->login($credentials, $options);      
$result = ($result) ? 1 : 0;

echo json_encode( array('loggedIn' => $result) );
jexit();

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