What are the best practices for securing PHP login forms against CSRF attacks, especially when using additional security tokens?

CSRF attacks can be prevented by using additional security tokens in PHP login forms. One common practice is to generate a unique token for each form submission and validate it on the server side to ensure that the request is legitimate. This helps protect against malicious attackers trying to trick users into submitting unauthorized requests.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
        die('Invalid CSRF token');
    }

    // Process login form
    // ...

    unset($_SESSION['token']);
}

$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
?>

<form method="post">
    <input type="hidden" name="token" value="<?php echo $token; ?>">
    <!-- Other form fields -->
    <button type="submit">Login</button>
</form>