get_user_id()
public function get_user_id(?string $token = null): int|bool
Description
Retrieves the user ID associated with a token. If no token is provided, checks session, cookie, and HTTP headers automatically.
This method is the primary way to identify the authenticated user in token‑based workflows (APIs, member areas).
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| $token | string|null | A 64‑character hexadecimal token. If null, the method searches session, cookie, and HTTP headers. | null | No |
Return Value
| Type | Description |
|---|---|
| int|bool |
|
Example Usage
PHP
// Get user ID from current request (auto‑detect token)
$user_id = $this->trongate_tokens->get_user_id();
if ($user_id !== false) {
echo "User ID: " . $user_id;
}
// Get user ID from a specific token (e.g., from API request)
$token = $_SERVER['HTTP_TRONGATETOKEN'] ?? null;
$user_id = $this->trongate_tokens->get_user_id($token);
// Protect an API endpoint
public function get_profile() {
$user_id = $this->trongate_tokens->get_user_id();
if ($user_id === false) {
http_response_code(401);
echo json_encode(['error' => 'Invalid token']);
die();
}
$profile = $this->model->get_profile($user_id);
echo json_encode($profile);
}
// Check if user is logged in
public function is_logged_in(): bool {
return $this->trongate_tokens->get_user_id() !== false;
}Notes
- Calls
$this->model->get_user_id($token)which validates token expiration. - Token search order when
$tokenis null: HTTP header → cookie → session. - Returns
falseif token is expired, invalid, or not found. - User ID corresponds to the
idcolumn in thetrongate_users(or custom users) table. - Use
get_user_obj()to get the full user object instead of just the ID.