delete_old_tokens()

public function delete_old_tokens(?int $user_id = null): void

Description

Deletes expired tokens from the database. Optionally deletes tokens for a specific user (both expired and non‑expired).

This method is useful for:

  • Routine cleanup of expired tokens (cron job)
  • Forcing logout of all sessions for a specific user
  • Reducing database bloat from stale tokens

Parameters

Parameter Type Description Default Required
$user_id int|null If provided, deletes all tokens for this user (regardless of expiration). If null, deletes only expired tokens for all users. null No

Return Value

Type Description
void This method does not return a value.

Example Usage

PHP
// Delete all expired tokens (routine cleanup)
$this->trongate_tokens->delete_old_tokens();

// Delete all tokens for a specific user (force logout)
$this->trongate_tokens->delete_old_tokens(123);

// Cron job script
public function cleanup_tokens() {
    $this->trongate_tokens->delete_old_tokens();
    echo "Expired tokens cleaned up.";
}

// Admin action: invalidate all user sessions
public function revoke_user_sessions(int $user_id) {
    $this->trongate_tokens->delete_old_tokens($user_id);
    set_flashdata('All sessions for user #' . $user_id . ' have been revoked.');
}

Notes

  • Calls $this->model->delete_old_tokens($user_id).
  • When $user_id is null, only tokens with expiry_date < NOW() are deleted.
  • When $user_id is provided, all tokens for that user are deleted (expired or not).
  • Consider running this method periodically (e.g., via cron) to keep the tokens table small.