2 回答
TA贡献1785条经验 获得超4个赞
如果您在表单上使用了 recaptcha,那么在提交表单时,PHP 中的 $_POST 将具有“g-recaptcha-response”。然后,您可以使用curl向Google发出API请求以验证他们的响应。
以下是非常基础的内容,未经测试。您将需要做更多的工作来改善用户体验,例如使用 Ajax
<?php
function verifyRecaptcha($response)
{
//Replace the below with your secret key
$recaptchaSecret = '<google_recaptcha_secret_key>';
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $recaptchaSecret,
'response' => $response,
));
$output = curl_exec($ch);
curl_close($ch);
//the response from Google will be a json string so decode it
$output = json_decode($output);
//one of the response keys is "success" which is a boolean
return $output->success;
}
//First filter the POSTed data
$email = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL);
$captchaResponse = filter_input(INPUT_POST,'g-recaptcha-response',FILTER_SANITIZE_STRING);
//If either email or catcha reponse is missing then one or both were not completed before submit
if(empty($email) || empty($captchaResponse))
{
//TODO: Better error handling here
echo "There was an error with the submitted data.";
}
elseif(!verifyRecaptcha($captchaResponse)) //this calls the above function to make the curl request
{
//TODO: Better error handling here
echo "Recaptcha verification failed.";
}
else
{
//I would suggest you don't use their email as the "From" address, rather it should be a domain
//that is allowed to send email from the server
//Instead you want to use their email as the "Reply-To" address
$formcontent = "From: $email \n";
$recipient = "contact@myemail.com";
$subject = "Subscribe";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "You have subscribed. You may close this tab now etc etc.";
}
TA贡献1856条经验 获得超11个赞
顺便说一句,这是形式:
<form class="form" action="mail5.php" method="POST">
<p class="email">
<input type="text" name="email" id="email" placeholder="mail@example.com" required />
</p>
<div class="g-recaptcha" data-sitekey="My Public Key"></div>
<p class="submit">
<input type="submit" value="Subscribe!" />
</p>
</form>
在我得到这个之前:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
- 2 回答
- 0 关注
- 129 浏览
添加回答
举报