What are some best practices for implementing token-based authentication in PHP scripts to prevent unauthorized access?

Token-based authentication in PHP scripts can help prevent unauthorized access by generating unique tokens for each user session. To implement this, you can create a token generation function that creates a random string for each user session and store this token in the user's session data. When a user makes a request, you can check if the token in the request matches the one stored in the session to authenticate the user.

// Token generation function
function generateToken() {
    return bin2hex(random_bytes(16));
}

// Start session
session_start();

// Check if token exists in session, generate one if not
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = generateToken();
}

// Validate token
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token'])) {
    if ($_POST['token'] !== $_SESSION['token']) {
        // Unauthorized access
        die('Unauthorized access');
    }
}

// Use the token in your HTML form
echo '<form method="post">
        <input type="hidden" name="token" value="' . $_SESSION['token'] . '">
        <!-- Other form fields -->
        <button type="submit">Submit</button>
      </form>';