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
- What alternative approach can be used to store images in a PHP application instead of directly in a database?
- How can error messages be stored in an array and displayed on the form page without using Location headers?
- What are some best practices for securing PHP scripts that involve file uploads on a server?