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:

  1. HTTP header $_SERVER['HTTP_TRONGATETOKEN']
  2. Cookie $_COOKIE['trongatetoken']
  3. 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
  • int – Single user level (e.g., 1 for admin)
  • array – Multiple user levels (e.g., [1, 2])
  • null – Any user level (default)
null No

Return Value

Type Description
string|bool
  • string – Valid token (64‑character hex string)
  • false – No valid token found

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_tokens database table.
  • The method calls the model to validate token expiration and user‑level matching.
  • Use get_user_id(), get_user_obj(), or get_user_level() to extract user information from a valid token.