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

Creating a Simple PHP Wrapper for Google reCAPTCHA

Create a reusable PHP class for Google reCAPTCHA to protect web forms from spam that supports static methods, default keys with override options, and easy integration into forms. It simplifies displaying the reCAPTCHA widget and verifying responses.

Living Fully: Embracing Life Beyond the Fear of Death

Inspired by Natalie Babbitt's quote, this post explores the importance of living fully rather than fearing death. It offers insights on what constitutes a well-lived life and provides strategies for embracing each moment with authenticity and purpose.