Поскольку я использую классы, я помещаю это в функцию. Google ожидает, что метод будет POST. Вы можете сделать это с помощью file_get_contents
, установив параметры stream_context_create
.
Все остальное самоочевидно, $secretkey
- ваш секретный ключ рекапчи, а $captcha
- ваш $_POST['g-recaptcha-response']
.
https://www.php.net/manual/en/function.stream-context-create.php
function checkRecaptcha( $secretkey , $captcha ){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = [
'secret' => $secretkey ,
'response' => $captcha ,
'remoteip' => $_SERVER['REMOTE_ADDR'] ,
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query( $data )
]
];
$context = stream_context_create( $options );
$contents = file_get_contents( $url , false , $context );
$response = json_decode( $contents , true ); //convert to assoc array
// if you want to use objects, remove true from json decode and then use $response->success
if( ! $response["success"] ) {
return false;
}
return true;
}
Затем вы можете использовать его как:
<?php
function checkRecaptcha( $secretkey , $captcha ){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = [
'secret' => $secretkey ,
'response' => $captcha ,
'remoteip' => $_SERVER['REMOTE_ADDR'] ,
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query( $data )
]
];
$context = stream_context_create( $options );
$contents = file_get_contents( $url , false , $context );
$response = json_decode( $contents , true ); //convert to assoc array
// if you want to use objects, remove true from json decode and then use $response->success
if( ! $response["success"] ) {
return false;
}
return true;
}
if( isset($_POST['submit'] ) ) {
$secretkey = "XXX Correct key here XXX";
if( ! checkRecaptcha( $secretkey , $_POST['g-recaptcha-response'] ) ) {
//only set variables if passes recaptcha
//validate email address
if ( ! filter_var( $_POST['senderemail'] , FILTER_VALIDATE_EMAIL)) {
echo "Please provide a valid email";
die();
}
//ensure user doesn't post HTML
$user_name = strip_tags ( $_POST['sendername'] );
$user_context = strip_tags ( $_POST['sendercontext'] );
$user_message = strip_tags ( $_POST['sendermessage'] );
$email_body = "Name: $user_name.\n"."Email: {$_POST['senderemail']}.\n"."Context: $user_context.\n"."Message: $user_message.\n";
$header = "From: bla@simpleenglish.info \r\n";
$header .= "Reply-To: {$_POST['senderemail']} \r\n";
mail( 'bla@simpleenglish.com' , 'Simple English Contact' , $email_body , $header );
echo "Message sent successfully";
}else{
echo "Invalid Captcha. Please try again.";
}
}
?>