How effective is using a token as an additional security measure in PHP form handling?
Using a token as an additional security measure in PHP form handling can be very effective in preventing CSRF (Cross-Site Request Forgery) attacks. By generating a unique token for each form submission and validating it on the server side, you can ensure that the form data is coming from a trusted source.
<?php
session_start();
// Generate a unique token and store it in the session
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
// Add the token to the form as a hidden input field
echo '<form method="post">';
echo '<input type="hidden" name="token" value="' . $_SESSION['token'] . '">';
// Add other form fields here
echo '</form>';
// Validate the token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
die('Invalid token');
}
// Process form data
}
?>