我假设它只是机器人,但我怎么能阻止这种情况发生?我至少在这里有一些验证 - 输入和php中的HTML5“必需”。忘记客户端验证,如果我尝试发送它而不填写信息它将返回错误(使用php)。
如果我不能,机器人如何通过它发送?我还需要添加什么?
<?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");
}
答案 0 :(得分:2)
您只检查$ _POST变量中的错误。机器人可能正在使用GET提交表单,因此可以根据$ _POST变量的存在来设置你所设置的验证。
我建议验证所有请求变量:$ _REQUEST。或者,您可以检查是否存在任何后置变量,如果不存在,则返回错误 - 从而强制执行POST。