带有reCAPTCHA v2的ajax,jquery联系人表单-500 Internal Server Error - javascript

我有一个jquery / ajax联系表单,并尝试添加Google reCAPTCHA v2,但无法正常工作。在加入reCAPTCHA之前,该表格已经奏效。 reCAPTCHA出现了(尽管需要花费很多时间才能加载),并且我可以验证自己不是机器人(也需要花费很多时间),但是当我单击“提交”按钮时,会显示状态消息的位置包括代码在内的文本:

<!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> 

我不知道怎么了。我按照Google的说明进行了操作,并将其包括在我的代码之前:

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

并像这样整合我的表格:

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

我尝试了多种方法将其集成到mailer.php文件中而没有成功,而且我找不到许多专门针对v2的教程(不确定是否很重要)。我的最新版本的mailer.php基于我在example上找到的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("\r","\n"),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 = "[email protected]";
            $subject = "New message from $name";
            $email_content = "Name: $name\n";
            $email_content .= "Email: $email\n\n";
            $email_content .= "Message:\n$message\n";
            $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.";
}      
?>

这是与我的联系表单一起使用的app.js(尝试包含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.');
            }
        });

    });

});

autoload.php直接来自Google Github,我没有做任何更改:

<?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;
    }
});

我将衷心感谢您的帮助!

参考方案

好的,我修复了它。无法使用的原因之一是我必须在php.ini中启用allow_url_fopen。

然后,我完全更改了代码以摆脱该autoload.php和类错误。我没有更改app.js。正常工作的mailer.php现在看起来像这样:

<?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("\r","\n"),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 = "[email protected]";
          $subject = "New message from $name";
          $email_content = "Name: $name\n";
          $email_content .= "Email: $email\n\n";
          $email_content .= "Message:\n$message\n";
          $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.";
}      
?>

将App部署到实时服务器时出现500 Internal Server error - c#

我的ASP.Net Web应用程序在其中一个页面上上传了一个简单的Ajax文件,该文件在测试时可以在本地主机上正常运行,但是当我将其发布到网站时,出现500 Internal Server错误。以下是Google chrome控制台上的输出:POST http://switchclothing.andrewmwest.co.uk/StoreManager/U…

Mongo汇总 - javascript

我的收藏中有以下文件{ "_id": ObjectId("54490b8104f7142f22ecc97f"), "title": "Sample1", "slug": "samplenews", "cat": …

如何在JQuery中操作JSONArray - javascript

我有一个php函数,它以JSON返回此代码{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9at…

JavaScript中的字符串评估函数 - javascript

            JavaScript中是否有任何内置函数,例如Python中的eval内置函数?注意:eval函数将方程式作为字符串并返回结果。例如,假设变量x为2,则eval("2x+5")返回9。 参考方案 是的,JavaScript中也有eval函数。此外,该声明应有效用于评估,即eval("2*x+5"…

在两个值之间匹配并返回正则表达式 - javascript

我正在尝试使用正则表达式从字符串中获取值,该值是tt="和"&之间的文本的值因此,例如,"tt="Value"&"我只想从中得到单词"Value"。到目前为止,我已经有了:/tt=.*&/这给了我"tt=Value"&,然后,要…