Google Recaptcha v2 с формой электронной почты, дает ошибку HTTP 500 - PullRequest
1 голос
/ 08 мая 2019

Использование HTML-формы для «свяжитесь с нами».Это передает имя, электронную почту и сообщение в скрипт .php, и это работает хорошо.Добавление в эту форму Google recaptua v2 дает ошибку http 500.Этот пост и код были отредактированы, чтобы отразить учебник KaplanKomputing, предложенный Крисом Уайтом.

Вы можете посетить рабочую форму без рекапитчи и нерабочего рекаптча здесь: https://coinsandhistory.com # contact

«Ключ сайта Google» я назову здесь «XXXX-Google-site» и «YYYY-Google-secret».

1-й контактный бланк html, вам не нуженCSS стиль и полоски из учебника.

<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer> 
</script>

<link rel="stylesheet" href="../css/send-mail.css">
</head>

<body>
<!-- https://stackoverflow.com/questions/27188436/html-php-contact-form- 
email/55962553 -->
<!-- https://kaplankomputing.com/blog/tutorials/
recaptcha-php-demo-tutorial/ -->
<form action="send-mail_SO2_recapt.php" method="post" 
enctype="multipart/form-data" name="myemailform">
<div>
<span>Name &nbsp;</span>
<input type="text" name="name" value="" placeholder="Your Name">
</div>
<div>
<span>Email &nbsp;</span>
<input type="email" name="web_email" autocapitalize="off" 
autocorrect="off" 
value="" placeholder="youremail@domain.com">
</div>

<div>
<span>messgae &nbsp;</span>
<textarea name="message" placeholder="message"></textarea>
</div>

<!--  Google v2 Recaptua Form   -->
<div class="g-recaptcha" data-sitekey="XXXX-Google-site"></div>
<br/>

<div class="code">
<button><input type="submit" name="submit" value="Send"></button>
</div>
<i class="clear" style="display: block"></i>
</div>
</form>
</body>
</html>

А затем скрипт send-mail.php.Я назвал мой "send-mail_SO2_recapt.php".

<?php
/* error reporting, should rmv from working form */
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST["name"];
$visitor_email = $_POST['web_email'];
$message = $_POST["message"];
$response = $_POST["g-recaptcha-response"];

//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are needed!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}

$url = "https://google.com/recaptcha/api/siteverify";
$data = array(
"secret" => "YYYY-Google-secret",
"response" => $_POST["g-recaptcha-response"]);
$options = array(
"https" => array (
"method" => "POST",
"content" => https_build_query($data)
)
);
$context  = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);

if ($captcha_success=>success==false) {
echo "<p>You are a bot! Go away!</p>"; }
else if ($captcha_success=>success==true) {
echo "<p>You are not not a bot!</p>";   }

// $email_from = 'info@coinsandhistory.com';//<== update the email address
$email_from = "$visitor_email";
$email_subject = "New Form submission";
$email_body = "You have received a new message from $name.\n".
"sender's email:\n $email_from\n".
"Here is the message:\n $message";

$to = "youremail@yourdomain.com";   //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank_you_SO2.html');
exit;

// Function to validate against any email injection attempts
?>

Если вы предоставляете примеры кода, пожалуйста, укажите, какая это форма: например, html, php, javascript.Я не могу поверить, что я первый, кто попытался использовать простое резюме Google в контактной форме, но этот вопрос явно нигде не появляется.

Ответы [ 2 ]

1 голос
/ 17 мая 2019

Вот ответ, который работал для меня.Я бы хотел поблагодарить Гальзора, потому что его ответы мне очень помогли.Базовый код, который я получил от Code Geek, и я добавил сюда материал для добавления в форму.Надеемся, что этот формат устраняет путаницу в том, что именно включать в Google "SITE-KEY" и "SECRET-KEY", так как он получает их как переменные перед обработкой их в строке.На самом деле это 40 строк символов.Успешная капча отправляется на целевую страницу.

Это HTML-код send-mail_form.html

<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

</head>

<body>
<!-- form goes in the body of HTML  -->
<form action="send-mail_form.php" method="post">

<div>
<span>Name</span>
<input type="text" name="name" value="" placeholder="Your Name" required>
</div>

<div>
<span>Email</span>
<input type="email" name="web_email" placeholder="youremail@domain.com" required>
</div>
<div>
<span>Messgae</span>
<textarea name="message" placeholder="message" required></textarea>
</div>

<!--  Google v2 Recaptcha Form   -->
<div class="g-recaptcha" data-sitekey="SITE-KEY"></div>
<div class="code">
<input type="submit" name="submit" value="Send">
</div>
</form>

</body>
</html>

И он будет называться send-mail_form.php.Я не буду показывать здесь файл thank_you_SO2.html.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$web_email;$message;$captcha;
// check form is submitted
if(isset($_POST['web_email']) ){

// get values
$name=            $_POST["name"];
$visitor_email=   $_POST['web_email'];
$message=         $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email)) {
$error = "Name and email are needed!";
}

if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}

if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}

$secretKey = "SECRET-KEY";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . 
urlencode($secretKey) .  '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// echo '<h3>Thanks for contacting us</h3>';

// mail then
$to = "youremail@yourdomain.com";
$email_subject = "CG Recaptcha Form2 submission";
$email_body = "You have received a new message from ".$name.".\n".
"sender's email:\n ".$visitor_email."\n".
"Here is the message:\n ".$message;

//Send the email!
$mail_check = mail($to,$email_subject,$email_body);
if( $mail_check ){
// echo "all is well. mail sent";
header('Location: thank_you_SO2.html');
}
else {
echo '<h2>You are a spammer ! Go Away</h2>';
}
}
}
?>

Есть некоторые ненужные элементы, проверка ошибок в верхней части может быть удалена.Также будет ли проверяться, что сайт Google будет работать с https://google.com/recaptcha/api/siteverify?secret=....?На самом деле при тестировании иногда кажется, что он не работает без www, так что, возможно, лучше сохранить его.

1 голос
/ 14 мая 2019

Я вижу количество ошибок в вашем коде.попробуйте следующий код и посмотрите, работает ли он, он протестирован и работает для меня.он не основан на вашем последующем уроке и вместо этого использует curl для проверки.

Ваши самые большие ошибки, я думаю, в том, что не определена isInfected определенная функция, => в -> и иногда file_get_contents Работает на всех серверах.

HTML:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="" method="post">
  <div>
    <span>Name</span>
    <input type="text" name="name" placeholder="Your Name" required>
  </div>
  <div>
    <span>Email</span>
    <input type="email" name="web_email" placeholder="youremail@domain.com" required>
  </div>
  <div>
    <span>Messgae</span>
    <textarea name="message" placeholder="message" required></textarea>
  </div>
  <!--  Google v2 Recaptcha Form   -->
  <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
  <div class="code">
    <input type="submit" name="submit" value="Send">
  </div>
</form>

КОД PHP:

<?php
//check form is submitted
if( isset($_POST['submit']) ){

  // get values
  $error = '';
  $name          = $_POST["name"];
  $visitor_email = $_POST['web_email'];
  $message       = $_POST["message"];

  //Validate first
  if(empty($name)||empty($visitor_email)) {
    $error = "Name and email are needed!";
  }

  //handle captcha response
  $captcha = $_REQUEST['g-recaptcha-response'];
  $handle = curl_init('https://www.google.com/recaptcha/api/siteverify');
  curl_setopt($handle, CURLOPT_POST, true);
  curl_setopt($handle, CURLOPT_POSTFIELDS, "secret=YOUR_SECRET_KEY&response=$captcha");
  curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($handle);
  $explodedArr = explode(",",$response);
  $doubleExplodedArr = explode(":",$explodedArr[0]);
  $captchaConfirmation = end($doubleExplodedArr);
  print_r($doubleExplodedArr);
  if ( trim($captchaConfirmation) != "true" ) {
    $error = "<p>You are a bot! Go away!</p>";
  }

  if( empty($error) ){ //no error
    // mail than
    $to = "youremail@mail.com";
    $email_subject = "New Form submission";
    $email_body = "You have received a new message from ".$name.".\n".
    "sender's email:\n ".$visitor_email."\n".
    "Here is the message:\n ".$message;
    $headers = "From: ".$visitor_email." \r\n";
    $headers .= "Reply-To: ".$visitor_email." \r\n";
    //Send the email!
    $mail_check = mail($to,$email_subject,$email_body,$headers);
    if( $mail_check ){
      // echo "all is well. mail sent";
      header('Location: thank_you.html');
    } else {
      echo "mail failed. try again";
    }
  } else {
    echo $error;
  }
}
?>
...