duanke8011 2016-11-09 23:42
浏览 69
已采纳

ajax,jquery联系表单与reCAPTCHA v2 - 500内部服务器错误

I have a jquery/ajax contact form and tried to add the Google reCAPTCHA v2, but it isn't working. The form worked before I included the reCAPTCHA. The reCAPTCHA shows up (although it takes forever to load), and I can verify that I'm not a robot (which takes forever as well), but when I click on my submit button, the spot where I display my status messages shows this, including the code, as text:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>500 Internal Server Error</title> </head><body> <h1>Internal Server Error</h1> <p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.</p> <p>More information about this error may be available in the server error log.</p> </body></html> 

I can't figure out what's going wrong. I followed Google's instructions and included this just before my tag:

<script src='https://www.google.com/recaptcha/api.js'></script>

and integrated my form like this:

<div class="g-recaptcha" data-sitekey="6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7"></div>

I tried many different ways to integrate it in my mailer.php file without success, and I couldn't find many tutorials that address v2 specifically (not sure if it even matters). My most recent version of the mailer.php is based on an example I found on Google's recaptcha Github:

<?php
require_once __DIR__ . 'inc/autoload.php';
// If the form was submitted    
if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // If the Google Recaptcha box was clicked
  if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
        $siteKey = '6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7';
        $secret = 'I-removed-this-for-now';
        $recaptcha = new \ReCaptcha\ReCaptcha($secret);            
        $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);

        // If the Google Recaptcha check was successful
        if ($resp->isSuccess()){
            $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("","
"),array(" "," "),$name);
            $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
            $message = trim($_POST["message"]);
            if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                http_response_code(400);
                echo "Oops! There was a problem with your submission. Please complete the form and try again.";
                exit;
            }
            $recipient = "I-removed-this@for-now.com";
            $subject = "New message from $name";
            $email_content = "Name: $name
";
            $email_content .= "Email: $email

";
            $email_content .= "Message:
$message
";
            $email_headers = "From: $name <$email>";
            if (mail($recipient, $subject, $email_content, $email_headers)) {
                http_response_code(200);
                echo "Thank You! Your message has been sent.";
            } 

            else {
                http_response_code(500);
                echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
            }

        } 

        // If the Google Recaptcha check was not successful    
        else {
            echo "Robot verification failed. Please try again.";
        }

    } 

    // If the Google Recaptcha box was not clicked   
    else {
        echo "Please click the reCAPTCHA box.";
    }      

} 

// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.         
else {
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}      
?>

This is the app.js that goes with my contact form (I haven't changed this at all when trying to include the reCAPTCHA):

$(function() {

    // Get the form.
    var form = $('#ajax-contact');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#message').val('');
        })
        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured, and your message could not be sent.');
            }
        });

    });

});

The autoload.php comes directly from the Google Github, and I didn't make any changes:

<?php

/* An autoloader for ReCaptcha\Foo classes. This should be required()
 * by the user before attempting to instantiate any of the ReCaptcha
 * classes.
 */

spl_autoload_register(function ($class) {
    if (substr($class, 0, 10) !== 'ReCaptcha\\') {
      /* If the class does not lie under the "ReCaptcha" namespace,
       * then we can exit immediately.
       */
      return;
    }

    /* All of the classes have names like "ReCaptcha\Foo", so we need
     * to replace the backslashes with frontslashes if we want the
     * name to map directly to a location in the filesystem.
     */
    $class = str_replace('\\', '/', $class);

    /* First, check under the current directory. It is important that
     * we look here first, so that we don't waste time searching for
     * test classes in the common case.
     */
    $path = dirname(__FILE__).'/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;
    }

    /* If we didn't find what we're looking for already, maybe it's
     * a test class?
     */
    $path = dirname(__FILE__).'/../tests/'.$class.'.php';
    if (is_readable($path)) {
        require_once $path;
    }
});

I would really appreciate your help!

  • 写回答

1条回答 默认 最新

  • douxigai8757 2016-11-10 08:50
    关注

    Okay, I fixed it. One reason it wasn't working was that I had to enable allow_url_fopen in php.ini.

    Then I completely changed the code to get rid of that autoload.php and the class error. I didn't change app.js. The working mailer.php now looks like this:

    <?php
    // If the form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
        // If the Google Recaptcha box was clicked
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
            $captcha=$_POST['g-recaptcha-response'];
            $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
            $obj = json_decode($response);
    
            // If the Google Recaptcha check was successful
            if($obj->success == true) {
              $name = strip_tags(trim($_POST["name"]));
              $name = str_replace(array("","
    "),array(" "," "),$name);
              $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
              $message = trim($_POST["message"]);
              if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                http_response_code(400);
                echo "Oops! There was a problem with your submission. Please complete the form and try again.";
                exit;
              }
              $recipient = "I-removed-this@for-now.com";
              $subject = "New message from $name";
              $email_content = "Name: $name
    ";
              $email_content .= "Email: $email
    
    ";
              $email_content .= "Message:
    $message
    ";
              $email_headers = "From: $name <$email>";
              if (mail($recipient, $subject, $email_content, $email_headers)) {
                http_response_code(200);
                echo "Thank You! Your message has been sent.";
              } 
    
              else {
                http_response_code(500);
                echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
              }
    
          } 
    
          // If the Google Recaptcha check was not successful    
          else {
            echo "Robot verification failed. Please try again.";
          }
    
      } 
    
      // If the Google Recaptcha box was not clicked   
      else {
        echo "Please click the reCAPTCHA box.";
      }      
    
    } 
    
    // If the form was not submitted
    // Not a POST request, set a 403 (forbidden) response code.         
    else {
      http_response_code(403);
      echo "There was a problem with your submission, please try again.";
    }      
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?