简体   繁体   中英

Contact form is sending blank emails

I'm assuming it's just bots, but how can I stop this from happening? I at least have some validation at work here - both HTML5 "required" in the inputs and php. Forgetting the client side validation, if I try to send it without filling in info it will return an error (with php).

How can bots send it through then if I can't? What do I need to add to this?

<?php
    $allowedFields = array(
        'firstname',
    'lastname',
    'email',
    'phone',
    'address',
    'prefer-email',
    'prefer-snail ',
);

$requiredFields = array(
        'firstname',
    'lastname',
    'email',
    'phone',
    'address',
    'prefer-email',
    'prefer-snail ',
);

$requiredEmail = array(
    'email',
);

$errors = array();
foreach($_POST AS $key => $value) {
    // first need to make sure this is an allowed field
    if(in_array($key, $allowedFields)) {
    $$key = $value;

    // is this a required field?
    if(in_array($key, $requiredFields) && $value == '') {
        $errors[] = "The field $key is required.";
    }

    // is this a required field?
    if(in_array($key, $requiredEmail) && !filter_var($value, FILTER_VALIDATE_EMAIL))    {
        $errors[] = "A valid email is required.";
    }
    }   
}

// were there any errors?
if(count($errors) > 0) {
    $errorString = '<div class="error2"><h1>There was an error with the form.</h1><br />';
    $errorString .= '<ul>';
    foreach($errors as $error) {
        $errorString .= "<li>$error</li>";
    }
    $errorString .= '</ul></div>';

    // display the previous form
    include 'index.php';
} else {
    $first_name = $_POST['firstname'];
    $last_name = $_POST['lastname'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $preferemail = $_POST['prefer-email'];
    $prefersnail = $_POST['prefer-snail'];


    $formcontent = "$firstname $lastname \r\n$email \r\n$phone \r\n$address \r\nPrefer Samples By: $preferemail $prefersnail \r\n";
    //$recipient = "Tester <test@test.com>";
    $recipient = "Tester <test@test.com>";
    $subject = "Test.com Form Submission";
    //$mailheader = "Landing Page <test@test.com>";
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
        header("Location: http://www.test.com/thanks.html");
}

You are only checking for errors in $_POST variables. Bots may be using GET to submit the form, therefore side-stepping the validation you've set up that is dependent on the presence of $_POST variables.

I'd recommend validating on all request variables: $_REQUEST. Alternatively, you can check if any post variables exist, and if not, return the error - thereby forcing a POST.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM