How to Create a User Account in Joomla with PHP

Below is a snippet on how to create a new Joomla! user account.

/**
 * Helper method to create a Joomla! User account
 *
 * @param   String  $username           The account's username
 * @param   String  $name               The account's name
 * @param   String  $email              The account's email address
 * @param   String  $password           The account's password
 * @param   Array   $groups             Comma separated Joomla! User Groups. Defaults to 2 = Registered.
 * @param   Bool    $activate           If set to true, the account will be activated without a confirmation e-mail.
 *
 * @throws  Exception
 * @return  Mixed   Object on success
 */
function addJoomlaUser($username, $name, $email, $password, $groups, $activate = false)
{
	jimport('joomla.user.helper');

	$data = [
        'name'   	 => $name,
        'username'	 => $username,
        'password'	 => $password,
        'password2'	 => $password,
        'email'		 => JStringPunycode::emailToPunycode($email),
        'groups'	 => explode(',', $groups)
	];

	if (!$activate)
	{
        $hash = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
		$data['activation'] = $hash;
		$data['block'] = 1;
	}

	// Load the users plugin group.
	JPluginHelper::importPlugin('user');
	
	$user = new JUser;
	
	if(!$user->bind($data))
	{
        throw new Exception($user->getError());
	}

	if (!$user->save())
	{
        throw new Exception($user->getError());
    }

    return $user;
}

// Create an inactive account. User will need to click on the confirmation e-mail.
$new_user = addJoomlaUser('johndoe', 'John Doe', '[email protected]', '123456', '2');

// Create an active user account. No confirmation e-mail will be sent.
$new_user = addJoomlaUser('johndoe', 'John Doe', '[email protected]', '123456', '2', true);
Last updated on Nov 28th 2024 09:11