How to Authenticate and Login a User with a Custom Joomla Form

Published in Convert Forms
Updated 05 Apr, 2021
Heads up! This article contains PHP code and is intended for developers. We offer this code as a courtesy, but don't provide support for code customizations or 3rd party development.

Would you like to create your own Login form, authenticate your users and redirect them to a specific page? The following PHP snippet will allow you to easily create a login form.

Setup

To create a login form, copy the code shown below and place it into the PHP Scripts -> Form Process area of your form.

// The field representing the username
$username = $post['username'];

// The field representing the password
$password = $post['password'];

// The message that will appear when both fields are not filled
$fill_fields = 'Please enter a username and password';

// The message that will appear when a user does not exist given its username
$user_does_not_exist = 'User does not exist';

// The message that will appear when an invalid password is given.
$invalid_password = 'Invalid password';

// Message that appears when Joomla cannot validate the user
$login_failed = 'Login Failed';

// Do not edit below
if (empty($username) || empty($password))
{
    throw new Exception($fill_fields);
}

$query = $db->getQuery(true)
	->select('id, password')
	->from('#__users')
	->where('username=' . $db->quote($username));

$db->setQuery($query);

if (!$result = $db->loadObject())
{
    throw new Exception($user_does_not_exist);
}

// Validate login credentials
if (JUserHelper::verifyPassword($password, $result->password, $result->id))
{
    $credentials = [
		'username' => $username,
    	'password' => $password
	];

    //perform log in
    $response = $app->login($credentials);

    if (!$response)
	{
		throw new Exception($login_failed);
	}
}
else
{
    throw new Exception($invalid_password);
}

Frequently Asked Questions

How can I redirect the user after they have successfully logged-in?

To redirect the user after they have successfully logged-in, you will need to go to Submission > Successful Submission Action > Redirect user > Redirect URL > Enter your redirect URL.

Once a user is logged-in there is no point in still showing the login form so a replacement would be to display a Logout link instead. To do so go to Behavior > PHP Scripts > Form Display and add the following PHP snippet:

if ($user->id) {
	$userToken = JSession::getFormToken();
	$formLayout = 'Logout';
}

This will display a link "Logout" which will allow your users to log out of your site. You may customize it to fit your needs.