Joomla 4 用户以编程方式登录

问题描述 投票:0回答:2

在 Joomla 3x 中,我有这个代码来登录用户,效果很好。

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

但是在 Joomla 4.2 中它说错误。

error

如何解决?谢谢!

authentication joomla joomla4
2个回答
1
投票

我找到了这段代码,它适用于 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();

0
投票

试试这个。您的代码已修复,可与 Joomla 4、5 和 6 一起使用

//Get the log in options.
$options = array();
$options['remember'] = 1;//this will keep user logged in
$options['return']   = '';

//Get the log in credentials
$credentials = array();
$credentials['username']  = $username;
$credentials['password']  = $password;
$credentials['secretkey'] = '';

$login_result = Factory::getApplication()->login($credentials, $options);

if (!$login_result) {
 //login failed
}
© www.soinside.com 2019 - 2024. All rights reserved.