Add CSRF protection and rate limiting to contact form
Improve contact form styling with dedicated CSS file Move contact form styles from base.css to separate file Add security measures to custom directory with .htaccess Update honeypot field styling and implementation
This commit is contained in:
parent
c013c2cde3
commit
7e44e7e132
4 changed files with 126 additions and 92 deletions
|
|
@ -5,10 +5,25 @@ $formSuccess = false;
|
|||
$formErrors = [];
|
||||
$formData = ['name' => '', 'email' => '', 'message' => ''];
|
||||
|
||||
// Start session for CSRF token and rate limiting
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Generate CSRF token if not exists
|
||||
if (empty($_SESSION['csrf_token'])) {
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
// Process form submission
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['contact_form_submit'])) {
|
||||
$formSubmitted = true;
|
||||
|
||||
// Security: CSRF Token Validation
|
||||
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
|
||||
$formErrors[] = 'Ugyldig sikkerhetskode. Vennligst prøv igjen.';
|
||||
}
|
||||
|
||||
// Spam Prevention 1: Honeypot field (should be empty)
|
||||
if (!empty($_POST['website'])) {
|
||||
$formErrors[] = 'Spam detected.';
|
||||
|
|
@ -32,10 +47,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['contact_form_submit']
|
|||
}
|
||||
|
||||
// Spam Prevention 4: Rate limiting (session-based)
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
$lastSubmitTime = isset($_SESSION['last_contact_submit']) ? $_SESSION['last_contact_submit'] : 0;
|
||||
if (time() - $lastSubmitTime < 60) {
|
||||
$formErrors[] = 'Vennligst vent litt før du sender inn igjen.';
|
||||
|
|
@ -208,11 +219,14 @@ $currentTime = time();
|
|||
<?php if (!$formSuccess): ?>
|
||||
<form method="post" action="<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?>" class="contact-form-inner">
|
||||
<!-- Honeypot field (hidden from users, bots will fill it) -->
|
||||
<div style="position: absolute; left: -5000px;" aria-hidden="true">
|
||||
<div class="hp-field" aria-hidden="true">
|
||||
<label for="website">Website</label>
|
||||
<input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
|
||||
</div>
|
||||
|
||||
<!-- CSRF Token -->
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
|
||||
|
||||
<!-- Time-based token -->
|
||||
<input type="hidden" name="form_start_time" value="<?= $currentTime ?>">
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue