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, we check if user already exists against the email.

public function checkUser($email)
{
$db = JFactory::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 details 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 new_user($data)
{
// Initialise the table with JUser
$user = new JUser;

$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['user_group'];

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

return $user;
}

 

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive