Create Joomla User Programmatically

You can create a new Joomla user in your extension (module, plugin or component) easily. At minimum, you need an email to create new user.

Step 1: Check for existing User

First, you check if user already exists against the email.

public function check_user($email)
{
$db = Factory::getDbo();
$query = $db->getQuery(true);

$query
->select('*')
->from($db->quoteName('#__users'))
->where($db->quoteName('email') . ' = ' . $db->quote($email))
->setLimit('1');

$db->setQuery($query);

$user = $db->loadObject();

return $user;
}

The function will either return the user object or null value.

Step 2: Create New User

The variable $data is an array containing user details. To create a new user, you need email, username, name, password and user group id.

public function create_new_user($data)
{
// Initialise the table with User
$user = new User;

$userdata = array();

// Set username as email
if (empty($data['username']))
{
$data['username'] = $data['email'];
}

// Set name
if (empty($data['name']))
{
$data['name'] = ucfirst(strstr($data['email'], '@', true));
}

// Set password as six digit random number
if (empty($data['password']))
{
$data['password'] = '';
for ($i = 0; $i < 6; $i++)
{
$data['password'] .= mt_rand(1,9);
}
$userdata['requireReset'] = 1;
}

$userdata['password'] = $data['password'];
$userdata['username'] = $data['username'];
$userdata['name'] = $data['name'];
$userdata['email'] = $data['email'];

$userdata['block'] = 0;

$userdata['groups'] = array();
$userdata['groups'][] = $data['groups'];

$user->bind($userdata);
$user->save();

return $user;
}

The function creates a new user and returns the user object.