Trongate PHP Framework Docs
Introduction
Quick Start
Basic Concepts
Understanding Routing
Intercepting Requests
Module Fundamentals
Database Operations
Templates
Helpers
Form Handling
Form Validation
Working With Files
Image Manipulation
Working With Dates & Times
Language Control
Security
Tips And Best Practices

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:

PHP
public function destroy(): void

This method takes no parameters and performs a complete cleanup.

What destroy() Does

When you call destroy(), the framework:

  1. Clears the session token
    • Unsets $_SESSION['trongatetoken']
  2. Destroys the cookie token
    • Sets $_COOKIE['trongatetoken'] to expire in the past
  3. Deletes tokens from the database
    • Removes the current user's tokens from trongate_tokens table
  4. 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
<?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:

PHP
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
<?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

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

Usage 1: Clean up all expired tokens

PHP
$this->trongate_tokens->delete_old_tokens();

This removes all tokens where expiry_date < current_time.

Usage 2: Delete all tokens for a specific user

PHP
$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

PHP
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

PHP
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
<?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:

BASH
0 2 * * * /usr/bin/php /path/to/your/app/index.php maintenance/clean_expired_tokens

This 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

PHP
public function logout(): void {
    $this->trongate_tokens->destroy();
    redirect('welcome');
}

Pattern 2: Logout with Message

PHP
public function logout(): void {
    $this->trongate_tokens->destroy();
    set_flashdata('You have been logged out');
    redirect('members/login');
}

Pattern 3: Force Logout All Devices

PHP
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.

Leave Feedback About This Page