How can implementing CSRF tokens or unique indexes in PHP forms help prevent duplicate database entries upon page refresh?
When a user refreshes a page after submitting a form, it can lead to duplicate database entries being created. Implementing CSRF tokens or unique indexes in PHP forms can help prevent this by ensuring that each form submission is unique and can only be processed once.
<?php
session_start();
// Generate CSRF token
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
// Check CSRF token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die("CSRF token validation failed.");
}
// Process form submission and insert data into database
}
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
Related Questions
- In the context of PHP development, why is it important to understand the difference between mysql_query and mysql_real_escape_string functions?
- What are the benefits of integrating CSS styles into PHP-generated HTML output for better presentation?
- What role does server configuration play in preventing SESSION key vulnerabilities in PHP?