attempt_get_valid_token()
public function attempt_get_valid_token(int|array|null $user_levels = null): string|bool
Description
Attempts to validate and return a valid token from HTTP headers, cookies, or session. Optionally filters tokens by user level(s).
Checks for tokens in this order of priority:
- HTTP header
$_SERVER['HTTP_TRONGATETOKEN'] - Cookie
$_COOKIE['trongatetoken'] - Session
$_SESSION['trongatetoken']
If $user_levels is provided, only tokens belonging to users with those levels are considered valid.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| $user_levels | int|array|null |
|
null | No |
Return Value
| Type | Description |
|---|---|
| string|bool |
|
Example Usage
PHP
// Get any valid token (any user level)
$token = $this->trongate_tokens->attempt_get_valid_token();
if ($token !== false) {
echo "Valid token: " . $token;
}
// Get token only if user level is 1 (admin)
$admin_token = $this->trongate_tokens->attempt_get_valid_token(1);
// Get token for either level 1 or 2
$staff_token = $this->trongate_tokens->attempt_get_valid_token([1, 2]);
// API endpoint protection
public function api_endpoint() {
$token = $this->trongate_tokens->attempt_get_valid_token();
if ($token === false) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
die();
}
// Process request with valid token...
}Notes
- Tokens are 64‑character hexadecimal strings.
- User levels are integer values stored in the
trongate_tokensdatabase table. - The method calls the model to validate token expiration and user‑level matching.
- Use
get_user_id(),get_user_obj(), orget_user_level()to extract user information from a valid token.