我已经用PHP为网站的联系表单设置了验证码,并且工作正常,除了当机器人试图进行提交时,我不断收到错误报告时。
由于这对我(人类)很好,所以我不确定出什么问题或如何进行测试。我尝试了许多变体,但似乎无法实时重新创建错误。
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//First Take care of Captcha
$captcha=$_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$secretkey = "MYSECRETKEY";
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
$captcha_fail = '<p style="color:red;"><strong>Please verify you are not a robot.</strong></p>';
} else { //If captcha succeeds
//Return clean version of a string
function spam_scrubber($value) {
//List of Bad Values
$very_bad = ['to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:'];
//If any of the bad values in the submitted form, return the string as empty
foreach ($very_bad as $v) {
if (stripos($value, $v) !== false) return '';
}
//Replace any nrewline characters with spaces
$value = str_replace(["\r", "\n", "%0a", "%0d"], ' ', $value);
//Return value;
return trim($value);
} //End of spam_scrubber function
//Clean the form data:
$scrubbed = array_map('spam_scrubber', $_POST);
if (!empty($scrubbed['name']) && !empty($scrubbed['email']) && !empty ($scrubbed['comments']) ) {
//Create the Body
$body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}";
//Make it wrap at 70 characters
$body = wordwrap($body,70);
//Send the email
mail('sales@example.com, 'Contact Form Submission', $body, "From: {$scrubbed['email']}");
//Print a message
echo '<p><strong>Thank you. Someone will get back with you as soon as possible.</strong></p>';
// Clear $_POST and scrubbed so form isn't sticky
$scrubbed = [];
$_POST = [];
} else {
echo '<p style="color:red;"><strong>Please fill out all fields!</strong></p>';
}
} // end of captcha conditional
} // end of POST conditional
这是我得到的错误:未定义索引:g-recaptcha-response
POST数组中的信息清楚地表明这是垃圾邮件,可能是由机器人提交的。