Blocking Form Mail Spam

Published on Jan 29, 2007   //  Development

Spam

If  you use some type of form on your site that sends out an email you are most likely to get some type of malicious bot that finds it and tries to use it to send out spam. You can add a bit of PHP code to your script to prevent that.

<?php
if (!isset( $_SERVER['REQUEST_METHOD'] != “POST”) {
    exit(“<p>You did not press the submit button; this page should not be accessed directly.</p>”);
}
?>

This will check to see if the form was submitted from your own site and that the page was just not directly accessed. Place this code on the PHP page that your form submits to.

2 Comments to “Blocking Form Mail Spam”

  • A better way of doing this may be to check to make sure the referrer page if where the user should be coming from. This will protect against malicious users from making a form like yours and then sending it through your email (or whatever) script. You can also incorporate POST checking into it as well. So, it would look something like this:

    Just place this in the top of your processing script and replace URLWITHFORM with the full URL of your form (eg. http://example.com/contact.php).

  • Apparently the code didn’t show up above for some reason. So, maybe it’ll show up here:

    <?php
    if ($_SERVER['HTTP_REFERER'] != "URLWITHFORM") {
    die("You didn't come from the correct page.");
    }
    elseif (!isset( $_SERVER[’REQUEST_METHOD’] != “POST”) {
    die("You did not press the submit button; this page should not be accessed directly.");
    }
    ?>

    Hopefully the code will show up this time.