How does the process of token generation and validation work in PHP sessions to prevent session hijacking?
Session hijacking can be prevented by generating a unique token for each session and validating it on each request. This token should be stored in the session data and checked against the token sent by the client to ensure that the session is not being hijacked.
<?php
session_start();
// Generate a random token
$token = bin2hex(random_bytes(32));
// Store the token in the session data
$_SESSION['token'] = $token;
// Validate the token on each request
if ($_SESSION['token'] !== $_POST['token']) {
// Invalid token, handle the error
die('Invalid token');
}