Destroying Tokens
When a user logs out, you need to destroy their token. This removes it from their device and from the database, ensuring they can't access protected pages until they log in again.
The destroy() Method
Use the method to remove tokens completely:
public function destroy(): voidThis method takes no parameters and performs a complete cleanup.
What destroy() Does
When you call destroy(), the framework:
- Clears the session token
- Unsets
$_SESSION['trongatetoken']
- Unsets
- Destroys the cookie token
- Sets
$_COOKIE['trongatetoken']to expire in the past
- Sets
- Deletes tokens from the database
- Removes the current user's tokens from
trongate_tokenstable
- Removes the current user's tokens from
- Cleans up expired tokens
- Automatically purges all expired tokens from the database
The method automatically calls internally, so you don't need to clean up expired tokens manually during logout.
Basic Logout Example
Here's a simple logout method:
<?php
class Members extends Trongate {
public function logout(): void {
// Destroy the token
$this->trongate_tokens->destroy();
// Redirect to home page
redirect('welcome');
}
}That's it. Two lines of code for a complete logout.
Logout with Confirmation Message
Add a flashdata message to confirm successful logout:
public function logout(): void {
// Destroy the token
$this->trongate_tokens->destroy();
// Set success message
set_flashdata('You have been logged out successfully');
// Redirect to login page
redirect('members/login');
}Complete Logout Workflow
Here's a more complete example showing login and logout together:
<?php
class Members extends Trongate {
public function login(): void {
// Show login form
$data['view_file'] = 'login';
$this->templates->public($data);
}
public function submit_login(): void {
// Get credentials
$username = post('username');
$password = post('password');
// Validate
$member = $this->db->get_where_custom('username', $username, 'members');
if (!$member || !password_verify($password, $member->password)) {
set_flashdata('Invalid username or password');
redirect('members/login');
}
// Generate token
$token = $this->trongate_tokens->generate_token([
'user_id' => $member->trongate_user_id
]);
// Redirect to dashboard
redirect('members/dashboard');
}
public function dashboard(): void {
// Validate token
$token = $this->trongate_tokens->attempt_get_valid_token(2);
if ($token === false) {
redirect('members/login');
}
// Show dashboard
$data['view_file'] = 'dashboard';
$this->templates->members_area($data);
}
public function logout(): void {
// Destroy token
$this->trongate_tokens->destroy();
// Confirm and redirect
set_flashdata('You have been logged out successfully');
redirect('members/login');
}
}This example assumes you have a members_area template and a public template created.
What Happens If No Token Exists?
Calling destroy() when no token exists is safe. The method will:
- Not throw any errors
- Not cause any warnings
- Simply complete successfully
This means you can safely call destroy() even if you're not sure whether a user has a token.
Manual Token Cleanup
While destroy() automatically cleans up expired tokens, you might want to run manual cleanup as a maintenance task.
The delete_old_tokens() Method
public function delete_old_tokens(?int $user_id = null): voidUsage 1: Clean up all expired tokens
$this->trongate_tokens->delete_old_tokens();This removes all tokens where expiry_date < current_time.
Usage 2: Delete all tokens for a specific user
$this->trongate_tokens->delete_old_tokens($trongate_user_id);This removes all tokens for the specified user, regardless of expiry date.
When to Use Manual Cleanup
- Scheduled maintenance - Run via cron job to keep database clean
- User deletion - Remove all tokens when deleting a user account
- Security incidents - Force logout of specific users
- Password changes - Invalidate existing sessions when password changes
Example: Force Logout on Password Change
public function change_password(): void {
// Validate current user
$user = $this->trongate_tokens->get_user_obj();
if ($user === false) {
redirect('login');
}
// Update password in database
$new_password = password_hash(post('new_password'), PASSWORD_DEFAULT);
$this->db->update($member_id, ['password' => $new_password], 'members');
// Delete all tokens for this user (force re-login everywhere)
$this->trongate_tokens->delete_old_tokens($user->trongate_user_id);
// Redirect to login
set_flashdata('Password changed. Please log in again.');
redirect('members/login');
}This ensures the user must log in again on all devices after changing their password.
Example: Delete User Account and Tokens
public function delete_account(): void {
// Get current user
$user = $this->trongate_tokens->get_user_obj();
if ($user === false) {
redirect('login');
}
$trongate_user_id = $user->trongate_user_id;
// Delete from members table
$this->db->delete($member_id, 'members');
// Delete from trongate_users table
$this->db->delete($trongate_user_id, 'trongate_users');
// Delete all tokens for this user
$this->trongate_tokens->delete_old_tokens($trongate_user_id);
// Redirect
set_flashdata('Your account has been deleted');
redirect('welcome');
}Scheduled Maintenance with Cron
For large applications, schedule automatic cleanup:
<?php
class Maintenance extends Trongate {
public function __construct(?string $module_name = null) {
parent::__construct($module_name);
block_url($this->module_name);
}
public function clean_expired_tokens(): void {
$this->trongate_tokens->delete_old_tokens();
echo 'Expired tokens cleaned at ' . date('Y-m-d H:i:s');
}
}Set up a cron job to run daily:
0 2 * * * /usr/bin/php /path/to/your/app/index.php maintenance/clean_expired_tokensThis runs at 2 AM every day and purges expired tokens.
Security Considerations
- Always destroy tokens on logout - Never just redirect without calling
destroy() - Destroy tokens on password change - Force re-authentication after security changes
- Clean up on user deletion - Remove tokens when deleting user accounts
- Use HTTPS - Ensure tokens can't be intercepted during the logout process
- Run scheduled cleanup - Keep your database clean with regular maintenance
Common Patterns
Pattern 1: Simple Logout
public function logout(): void {
$this->trongate_tokens->destroy();
redirect('welcome');
}Pattern 2: Logout with Message
public function logout(): void {
$this->trongate_tokens->destroy();
set_flashdata('You have been logged out');
redirect('members/login');
}Pattern 3: Force Logout All Devices
public function force_logout_everywhere(): void {
$user = $this->trongate_tokens->get_user_obj();
$this->trongate_tokens->delete_old_tokens($user->trongate_user_id);
redirect('members/login');
}Chapter Summary
You now know how to:
- ✅ Understand the three security tables
- ✅ Generate tokens after successful login
- ✅ Validate tokens on protected pages
- ✅ Fetch user data from tokens
- ✅ Destroy tokens on logout
With these fundamentals, you can build complete authentication systems in Trongate.
What's Next?
Advanced topics to explore:
- API authentication with HTTP headers
- The Trongate Security module for scenario-based access control
- Building complete login/registration systems
- Multi-device session management
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.