What are the advantages of using a centralized token system for handling user form submissions in PHP?
When handling user form submissions in PHP, one common issue is preventing CSRF (Cross-Site Request Forgery) attacks. One way to mitigate this risk is by implementing a centralized token system. This involves generating a unique token for each form submission and verifying it on the server side to ensure that the request is legitimate.
<?php
session_start();
// Generate a unique token for the form submission
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
// Include this token in the form
echo '<form method="post">';
echo '<input type="hidden" name="csrf_token" value="' . $token . '">';
echo '<input type="text" name="username">';
echo '<input type="password" name="password">';
echo '<input type="submit" value="Submit">';
echo '</form>';
// Verify the token on form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// Token is valid, process the form submission
// Add your form processing logic here
} else {
// Token is invalid, handle the error
echo 'CSRF Token validation failed';
}
}
?>