我的表单需要一个验证码,我在服务器端集成方面遇到了一些麻烦.
表单包含四种类型的数据:
>名字
>电子邮件
>评论.
在确保它们都不为空之后,我想验证验证码.但是,由于某种原因,它总是返回成功== false.
有人可以帮我发现我的代码有什么问题吗?
function validate($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$nameMsgErr = $emailErr = $msgSuccess = $error = "";
if(!empty($_POST['name_msg']) && !empty($_POST['email']) && !empty($_POST['subject']) && !empty($_POST['message'])) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$private_key = '------Private Key--------';
$response = file_get_contents($url . "?secret=" . $private_key . "&response=" . $_HOST['g-recaptcha-response'] . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success == true) {
$name = validate($_POST['name_msg']);
$email = validate($_POST['email']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
} else {
$subject = validate($_POST['subject']);
$msg = validate($_POST['message']);
$msg .= "\r\n" . $name;
$msg = wordwrap($msg, 70, "\r\n");
$header = "From: " . $email;
mail("myemail9@gmail.com", $subject, $msg, $header);
$msgSuccess = "Message successfully sent";
}
} else {
$error = "Error";
}
}
解决方法:
您使用错误的HTTP方法来验证用户响应.在您的代码中,您使用file_get_contents并且它正在发送GET请求,该请求每次都返回false.
如documentation中所述,您需要向google recaptcha api发送POST请求.
有关使用file_get_contents发送POST请求,请参阅this答案
注意:cURL是发送POST请求的更常用方法,可能更容易掌握和实现.我建议使用cURL开始.
编辑(添加特定示例,未测试):
$postdata = http_build_query(
array(
'secret' => $private_key,
'response' => $_HOST["g-recaptcha-response"],
'remoteip' => $_SERVER["REMOTE_ADDR"]
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', FALSE, $context);