Skip to content
Steven Roland

Implementing Single-Use Tokens with PHP Sessions

PHP , HTML

In our previous exploration of CSRF tokens, we focused on basic token generation and validation. Now, let's shift our attention to creating single-use tokens without relying on a database, using PHP sessions instead. This approach can simplify implementation while still providing robust security for actions like form submissions and sensitive transactions.

Why Use Single-Use Tokens?

Single-use tokens enhance security by ensuring that each token is valid for only one transaction. This prevents replay attacks and ensures that once a token is used, it cannot be reused, thus protecting sensitive operations.

Generating Single-Use Tokens with Sessions

Using PHP sessions, we can generate, store, and validate single-use tokens without the need for a database. Here’s how you can implement this:

1. Token Generation

Generate a secure token using random_bytes() and store it in the session. This ensures that each token is unique and securely stored on the server side:

session_start();

function generateToken() {
    $token = bin2hex(random_bytes(32));
    $_SESSION['single_use_token'] = $token;

    return $token;
}

$token = generateToken();

2. Using the Token in Forms

Include the generated token in your form as a hidden input field. This allows you to send the token along with the form data for validation:

<form method="post" action="process_form.php">
    <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
    <!-- Other form fields -->
    <button type="submit">Submit</button>
</form>

3. Validating and Consuming the Token

Upon form submission, validate the token by comparing it with the one stored in the session. If valid, proceed with the action and remove the token from the session to ensure it cannot be reused:

session_start();

function validateToken($receivedToken) {
    if (isset($_SESSION['single_use_token']) && hash_equals($_SESSION['single_use_token'], $receivedToken)) {
        // Token is valid, consume it
        unset($_SESSION['single_use_token']);
        return true;
    }
    return false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (validateToken($_POST['token'])) {
        // Proceed with the action
    } else {
        // Handle invalid token
        echo "Invalid or expired token.";
    }
}

Advantages of Using Sessions

  • Simplicity: No need to manage a database, which simplifies the implementation.

  • Security: Tokens are stored server-side, reducing the risk of exposure.

  • Efficiency: Session-based storage is generally faster for small-scale applications.

Best Practices

  • Session Management: Ensure sessions are managed securely, with appropriate session timeouts and regeneration of session IDs to prevent session hijacking.

  • HTTPS: Always use HTTPS to ensure tokens are transmitted securely.

  • Token Expiration: Consider implementing a mechanism to expire tokens after a certain period to enhance security further.

By leveraging PHP sessions for single-use tokens, you can maintain a secure and efficient method of protecting sensitive operations without the complexity of database management. This approach is particularly suitable for applications where simplicity and security are both priorities.

Support My Work

If you enjoy my content, consider supporting me through Buy Me a Coffee or GitHub Sponsors.

Buy Me A Coffee
or

More posts

Laravel with a Legacy Database

If you ever need to work with a database that doesn't quite follow convention, remember that Laravel has some pretty sweet built-in functionality to help you use that old data in new ways.

How to Identify and Deal with a Narcissist

Learn to identify narcissists by their grandiosity, need for admiration, and lack of empathy. Manage relationships by setting boundaries, communicating clearly, and seeking support. Prioritize your well-being and consider professional help if needed.

The Myth of Medusa: Unraveling the Stone-Gazing Curse

Medusa, a Greek mythological figure, could turn anyone to stone with her gaze. Her story evolved from a monstrous figure to a tragic victim, symbolizing themes of transformation and resilience, and remains a powerful cultural symbol today.