Skip to content

XOOPS User System

The XOOPS User System manages user accounts, authentication, authorization, group membership, and session management. It provides a robust framework for securing your application and controlling user access.

graph TD
A[User System] -->|manages| B[XoopsUser]
A -->|manages| C[XoopsGroup]
A -->|handles| D[Authentication]
A -->|handles| E[Sessions]
D -->|validates| F[Username/Password]
D -->|validates| G[Email/Token]
D -->|triggers| H[Post-Login Hooks]
E -->|manages| I[Session Data]
E -->|manages| J[Session Cookies]
B -->|belongs to| C
B -->|has| K[Permissions]
B -->|has| L[Profile Data]
C -->|defines| M[Access Levels]
C -->|contains| N[Multiple Users]

The main user object class representing a user account.

namespace Xoops\Core\User;
class XoopsUser extends XoopsObject
{
protected int $uid = 0;
protected string $uname = '';
protected string $email = '';
protected string $pass = '';
protected int $uregdate = 0;
protected int $ulevel = 0;
protected array $groups = [];
protected array $permissions = [];
}
public function __construct(int $uid = null)

Creates a new user object, optionally loading from database by ID.

Parameters:

ParameterTypeDescription
$uidintUser ID to load (optional)

Example:

// Create new user
$user = new XoopsUser();
// Load existing user
$user = new XoopsUser(123);
PropertyTypeDescription
uidintUser ID
unamestringUsername
emailstringEmail address
passstringPassword hash
uregdateintRegistration timestamp
ulevelintUser level (9=admin, 1=user)
groupsarrayGroup IDs
permissionsarrayPermission flags

Gets the user’s ID.

public function getID(): int
public function getUid(): int // Alias

Returns: int - User ID

Example:

$user = new XoopsUser(1);
echo $user->getID(); // 1
echo $user->getUid(); // 1

Gets the user’s display name.

public function getUnameReal(): string

Returns: string - User’s real name

Example:

$realName = $user->getUnameReal();
echo "Hello, $realName";

Gets the user’s email address.

public function getEmail(): string

Returns: string - Email address

Example:

$email = $user->getEmail();
mail($email, 'Welcome', 'Welcome to XOOPS');

Gets or sets a user variable.

public function getVar(string $key, string $format = 's'): mixed
public function setVar(string $key, mixed $value, bool $notGpc = false): bool

Example:

// Get values
$username = $user->getVar('uname');
$email = $user->getVar('email', 's'); // Formatted for display
// Set values
$user->setVar('uname', 'newusername');
$user->setVar('email', 'user@example.com');

Gets the user’s group memberships.

public function getGroups(): array

Returns: array - Array of group IDs

Example:

$groups = $user->getGroups();
echo "Member of " . count($groups) . " groups";

Checks if user belongs to a group.

public function isInGroup(int $groupId): bool

Parameters:

ParameterTypeDescription
$groupIdintGroup ID to check

Returns: bool - True if in group

Example:

if ($user->isInGroup(1)) { // 1 = Webmasters
echo 'User is a webmaster';
}

Checks if user is an administrator.

public function isAdmin(): bool

Returns: bool - True if admin

Example:

if ($user->isAdmin()) {
// Show admin controls
echo '<a href="admin/">Admin Panel</a>';
}

Gets user profile information.

public function getProfile(): array

Returns: array - Profile data

Example:

$profile = $user->getProfile();
echo 'Bio: ' . $profile['bio'];

Checks if user account is active.

public function isActive(): bool

Returns: bool - True if active

Example:

if ($user->isActive()) {
// Allow user access
} else {
// Restrict access
}

Updates the user’s last login timestamp.

public function updateLastLogin(): bool

Returns: bool - True on success

Example:

if ($user->updateLastLogin()) {
echo 'Login recorded';
}

Manages user groups and permissions.

namespace Xoops\Core\User;
class XoopsGroup extends XoopsObject
{
protected int $groupid = 0;
protected string $name = '';
protected string $description = '';
protected int $group_type = 0;
protected array $users = [];
}
ConstantValueDescription
TYPE_NORMAL0Normal user group
TYPE_ADMIN1Administrative group
TYPE_SYSTEM2System group

Gets the group name.

public function getName(): string

Returns: string - Group name

Example:

$group = new XoopsGroup(1);
echo $group->getName(); // "Webmasters"

Gets the group description.

public function getDescription(): string

Returns: string - Description

Example:

echo $group->getDescription();

Gets group members.

public function getUsers(): array

Returns: array - Array of user IDs

Example:

$users = $group->getUsers();
echo "Group has " . count($users) . " members";

Adds a user to the group.

public function addUser(int $uid): bool

Parameters:

ParameterTypeDescription
$uidintUser ID

Returns: bool - True on success

Example:

$group = new XoopsGroup(2); // Editors
$group->addUser(123);
$groupHandler->insert($group);

Removes a user from the group.

public function removeUser(int $uid): bool

Example:

$group->removeUser(123);
/**
* User login
*/
function xoops_user_login(string $uname, string $pass, bool $rememberMe = false): ?XoopsUser
{
global $xoopsDB;
// Sanitize username
$uname = trim($uname);
// Get user from database
$query = $xoopsDB->prepare(
'SELECT * FROM ' . $xoopsDB->prefix('users') .
' WHERE uname = ? AND active = 1'
);
$query->bind_param('s', $uname);
$query->execute();
$result = $query->get_result();
if ($result->num_rows === 0) {
return null; // User not found
}
$row = $result->fetch_assoc();
// Verify password
if (!password_verify($pass, $row['pass'])) {
return null; // Invalid password
}
// Load user object
$user = new XoopsUser($row['uid']);
// Update last login
$user->updateLastLogin();
// Handle "Remember Me"
if ($rememberMe) {
// Set persistent cookie
setcookie(
'xoops_user_remember',
$user->uid(),
time() + (30 * 24 * 60 * 60), // 30 days
'/',
$_SERVER['HTTP_HOST'] ?? ''
);
}
return $user;
}
/**
* Hash password securely
*/
function xoops_hash_password(string $password): string
{
return password_hash($password, PASSWORD_BCRYPT, [
'cost' => 12
]);
}
/**
* Verify password
*/
function xoops_verify_password(string $password, string $hash): bool
{
return password_verify($password, $hash);
}
/**
* Check if password needs rehashing
*/
function xoops_password_needs_rehash(string $hash): bool
{
return password_needs_rehash($hash, PASSWORD_BCRYPT, [
'cost' => 12
]);
}
namespace Xoops\Core;
class SessionManager
{
protected array $data = [];
protected string $sessionId = '';
public function start(): void {}
public function get(string $key): mixed {}
public function set(string $key, mixed $value): void {}
public function destroy(): void {}
}
<?php
session_start();
// Regenerate session ID for security
session_regenerate_id(true);
// Set session timeout
ini_set('session.gc_maxlifetime', 3600); // 1 hour
// Store user in session
if ($user) {
$_SESSION['xoops_user'] = $user;
$_SESSION['xoops_uid'] = $user->getID();
$_SESSION['xoops_uname'] = $user->getVar('uname');
}
/**
* Get current user from session
*/
function xoops_get_current_user(): ?XoopsUser
{
if (isset($_SESSION['xoops_user']) && $_SESSION['xoops_user'] instanceof XoopsUser) {
return $_SESSION['xoops_user'];
}
return null;
}
/**
* Check if user is logged in
*/
function xoops_is_user_logged_in(): bool
{
return isset($_SESSION['xoops_uid']) && $_SESSION['xoops_uid'] > 0;
}
/**
* User logout
*/
function xoops_user_logout()
{
global $xoopsUser;
// Log the logout
if ($xoopsUser) {
error_log('User ' . $xoopsUser->getVar('uname') . ' logged out');
}
// Destroy session data
$_SESSION = [];
// Delete session cookie
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
// Destroy session
session_destroy();
}
ConstantValueDescription
XOOPS_PERMISSION_NONE0No permission
XOOPS_PERMISSION_VIEW1View content
XOOPS_PERMISSION_SUBMIT2Submit content
XOOPS_PERMISSION_EDIT4Edit content
XOOPS_PERMISSION_DELETE8Delete content
XOOPS_PERMISSION_ADMIN16Admin access
/**
* Check if user has permission
*/
function xoops_check_permission($user, $resource, $permission)
{
if (!$user) {
return false;
}
// Admins have all permissions
if ($user->isAdmin()) {
return true;
}
// Check group permissions
$groups = $user->getGroups();
foreach ($groups as $groupId) {
if (xoops_group_has_permission($groupId, $resource, $permission)) {
return true;
}
}
return false;
}

The UserHandler manages user persistence operations.

/**
* Get user handler
*/
$userHandler = xoops_getHandler('user');
/**
* Create new user
*/
$user = new XoopsUser();
$user->setVar('uname', 'newuser');
$user->setVar('email', 'user@example.com');
$user->setVar('pass', xoops_hash_password('password123'));
$user->setVar('uregdate', time());
$user->setVar('uactive', 1);
if ($userHandler->insert($user)) {
echo 'User created with ID: ' . $user->getID();
}
/**
* Update user
*/
$user = $userHandler->get(123);
$user->setVar('email', 'newemail@example.com');
$userHandler->insert($user);
/**
* Get user by name
*/
$user = $userHandler->findByUsername('john');
/**
* Delete user
*/
$userHandler->delete($user);
/**
* Search users
*/
$criteria = new CriteriaCompo();
$criteria->add(new Criteria('uname', '%admin%', 'LIKE'));
$users = $userHandler->getObjects($criteria);
<?php
/**
* Complete user authentication and profile example
*/
require_once XOOPS_ROOT_PATH . '/include/common.inc.php';
$xoopsUser = $GLOBALS['xoopsUser'];
// Check if user is logged in
if (!$xoopsUser || !$xoopsUser->isActive()) {
redirect_header(XOOPS_URL, 3, 'Please login');
}
// Get user handler
$userHandler = xoops_getHandler('user');
// Get current user with fresh data
$currentUser = $userHandler->get($xoopsUser->getID());
// User profile page
echo '<h1>Profile: ' . htmlspecialchars($currentUser->getVar('uname')) . '</h1>';
echo '<div class="user-profile">';
echo '<p><strong>Username:</strong> ' . htmlspecialchars($currentUser->getVar('uname')) . '</p>';
echo '<p><strong>Email:</strong> ' . htmlspecialchars($currentUser->getVar('email')) . '</p>';
echo '<p><strong>Registered:</strong> ' . date('Y-m-d H:i:s', $currentUser->getVar('uregdate')) . '</p>';
echo '<p><strong>Groups:</strong> ';
$groupHandler = xoops_getHandler('group');
$groups = $currentUser->getGroups();
$groupNames = [];
foreach ($groups as $groupId) {
$group = $groupHandler->get($groupId);
if ($group) {
$groupNames[] = htmlspecialchars($group->getName());
}
}
echo implode(', ', $groupNames);
echo '</p>';
// Admin status
if ($currentUser->isAdmin()) {
echo '<p><strong>Status:</strong> Administrator</p>';
}
echo '</div>';
// Change password form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['change_password'])) {
$oldPassword = $_POST['old_password'] ?? '';
$newPassword = $_POST['new_password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';
// Verify old password
if (!password_verify($oldPassword, $currentUser->getVar('pass'))) {
echo '<div class="error">Current password is incorrect</div>';
} elseif ($newPassword !== $confirmPassword) {
echo '<div class="error">New passwords do not match</div>';
} elseif (strlen($newPassword) < 6) {
echo '<div class="error">Password must be at least 6 characters</div>';
} else {
// Update password
$currentUser->setVar('pass', xoops_hash_password($newPassword));
if ($userHandler->insert($currentUser)) {
echo '<div class="success">Password changed successfully</div>';
} else {
echo '<div class="error">Failed to update password</div>';
}
}
}
// Password change form
echo '<form method="post">';
echo '<h3>Change Password</h3>';
echo '<div class="form-group">';
echo '<label>Current Password:</label>';
echo '<input type="password" name="old_password" required>';
echo '</div>';
echo '<div class="form-group">';
echo '<label>New Password:</label>';
echo '<input type="password" name="new_password" required>';
echo '</div>';
echo '<div class="form-group">';
echo '<label>Confirm Password:</label>';
echo '<input type="password" name="confirm_password" required>';
echo '</div>';
echo '<button type="submit" name="change_password">Change Password</button>';
echo '</form>';
  1. Hash Passwords - Always use bcrypt or argon2 for password hashing
  2. Validate Input - Validate and sanitize all user input
  3. Check Permissions - Always verify user permissions before actions
  4. Use Sessions Securely - Regenerate session IDs on login
  5. Log Activities - Log login, logout, and critical actions
  6. Rate Limiting - Implement login attempt rate limiting
  7. HTTPS Only - Always use HTTPS for authentication
  8. Group Management - Use groups for permission organization
  • ../Kernel/Kernel-Classes - Kernel services and bootstrapping
  • ../Database/QueryBuilder - Database queries for user data
  • ../Core/XoopsObject - Base object class

See also: XOOPS User API | PHP Security