Prevent php web contact form spam

Prevent php web contact form spam

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Prevent php web contact form spam

Your contact form has suddenly started receiving hundreds of submissions daily, all containing generated strings in the name field and valid-looking but likely fake email addresses. This is a classic brute-force attack where bots scan your site for _POST['email'] fields and hammer them with requests to test if your validation logic is weak or bypassed.

The root cause lies in your current PHP implementation. You are checking if(!isset($_POST['name']) ...) immediately after verifying the email exists, but you are sending the form data via a standard HTML form without any protection against automated tools. Bots do not care about your "Name" or "Comments" fields if they can simply leave them empty or fill them with random strings while targeting the email field.

The Problem with Your Current Logic

Your code currently relies entirely on server-side validation:

if (!isset($_POST['name']) || !isset($_POST['email']) || ...) {
    died('...');
}

This approach fails because bots can easily bypass isset() checks. They submit the form with empty values or random strings, satisfying the condition that the fields exist. Furthermore, your cleaning function removes specific headers like "content-type", but it does not verify that the data actually belongs to a human user.

Additionally, using the @mail() function is risky. It suppresses errors and often lacks proper authentication, making it easier for spammers to forge the Reply-To or From headers if you rely solely on client-provided data. The header construction in your code:

$headers = 'From: '.$email_from."\r\n" . "Reply-To: ".$email_from."\r\n";

uses the user-submitted email directly as the sender address. This is a major vulnerability; if a bot submits spam@evil.com, your server will appear to send from that address, potentially triggering spam filters on your inbox provider's side.

Implementing Rate Limiting Without Captcha

You requested a solution without distorted text tests (Captcha) and without forcing all fields to be filled. The most effective way to achieve this is through rate limiting at the application level. This denies service to IPs that submit too many requests in a short window, effectively stopping brute-force scripts while allowing legitimate users to fill out the form normally.

You can implement this using PHP's $_SERVER['REMOTE_ADDR'] combined with a simple file-based or database-based counter. For a static site, saving counts to a file is sufficient and requires no external dependencies.

Create a file named spam_log.txt in your uploads directory (ensure chmod 755 on the folder). Modify your PHP script to check this file before processing:

$max_submissions = 10; // Allow 10 submissions per hour
$ip_address = $_SERVER['REMOTE_ADDR'];
$log_file = __DIR__ . '/spam_log.txt';

// Initialize array if it doesn't exist
if (!file_exists($log_file)) {
    $submissions = [];
} else {
    $lines = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $submissions = [];
    foreach ($lines as $line) {
        if (preg_match('/^([0-9]+):([^:]+):(.+)$/u', trim($line), $matches)) {
            list($count, $ip, $timestamp) = $matches;
            $submissions[$ip] = intval($count);
        }
    }
}

$current_time = time();
$window_start = $current_time - 3600; // 1 hour window

// Filter out old entries and check current count
foreach ($submissions as $ip => $count) {
    if ($count > $max_submissions || $submissions[$ip] < $window_start) {
        continue; 
    }
    
    if (isset($submissions[$ip]) && ($current_time - $submissions[$ip] < 3600)) {
        died("Too many submissions from your IP address. Please wait an hour.");
    }
}

// If we reach here, log the submission
$submissions[$ip] = $current_time;
file_put_contents($log_file, implode("\n", array_map(function($data) { return $data[0] . ':' . $data[1] . ':' . $data[2]; }, array_values(array_combine(array_keys($submissions), $submissions))), PHP_EOL));

Note: The above logic is a simplified conceptual example. In production, you would need to persist counts more robustly or use a session-based approach if the site serves multiple users from the same IP.

A more practical implementation for a simple script involves maintaining a session variable to track submission frequency:

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ip = $_SERVER['REMOTE_ADDR'];
    
    // Check if we already hit the limit in this hour
    if (!isset($_SESSION['last_submission'])) {
        $_SESSION['last_submission'] = time();
    } else {
        $time_diff = time() - $_SESSION['last_submission'];
        if ($time_diff < 300) { // Less than 5 minutes between submissions
            died('Please wait a few minutes before submitting the form again.');
        }
    }

    $_SESSION['last_submission'] = time();
    
    // Proceed with your existing logic...
}

This method does not require filling all fields because it acts as a gatekeeper before validation occurs. It effectively blocks bots that hammer the submit button, while humans who take a moment to read the form pass through easily.

Secure Your Email Handling

Beyond rate limiting, you must stop using the user-submitted email for the From header. Instead, use your own domain's address. This prevents spammers from spoofing your reputation and ensures that replies go to you, not their botnet.

Update your headers like this:

$headers = "From: info@yourdomain.com\r\n" . 
           "Reply-To: info@yourdomain.com\r\n" . 
           "X-Mailer: PHP/" . phpversion();

Also, consider using filter_var() to validate the email format before sending, rather than just checking if it exists:

if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
    died('Invalid email format.');
}

Conclusion

By combining session-based rate limiting with strict header sanitization, you can stop the influx of spam without degrading the user experience. This approach respects your constraints: no Captcha and flexible field requirements. It treats the contact form as a service that should be protected from automated abuse just like any other API endpoint on your server.

Our network