PHP 和 Recaptcha v3 - 提交 PHP 表单时出错

问题描述 投票:0回答:0

我再次需要一些帮助,如果解决方案很愚蠢,我会提前道歉......

当我提交我的表单控制台时抛出以下错误:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at init.js:42:59 

第 42 行以 const 开头

代码:

fetch("/send.php", {
  method: "POST",
  body: new FormData(form), // Send the form data
})
  .then((response) => response.text())
  .then((response) => {
    const responseText = JSON.parse(response); // Get the response
    if (responseText.error !== "") {
      // If there is an error
      document.querySelector("#alert").innerText = responseText.error;
      document.querySelector("#alert").classList.add("error");
      document.querySelector(".formfields").style.display = "block";
      return;
    }
  });

除此之外,无论是否发送电子邮件,似乎都会触发 send.php。

代码:

<?php
/**
 * Check to see if all fields that are required have been submitted
 *
 * @return boolean
 */
function isValid(){
    if(
        $_POST['fname'] != '' &&
        $_POST['lname'] != '' &&
        $_POST['email'] != '' &&
        $_POST['message'] != ''
    ) {
        return true;
    }
    return false;
}

// Declare variables to prepare for form submission
$success_output = '';
$error_output = '';

if (isValid()) {
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'; // URL to the reCAPTCHA server
    $recaptcha_secret = 'redacted'; // Secret key
    $recaptcha_response = $_POST['recaptchaResponse']; // Response from reCAPTCHA server, added to the form during processing
    $recaptcha = file_get_contents($recaptcha_url.'?secret='.$recaptcha_secret.'&response='.$recaptcha_response); // Send request to the server
    $recaptcha = json_decode($recaptcha); // Decode the JSON response
    if($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == "contact"){ // If the response is valid
        // Set up the email message
        $to = '[email protected]'; // Change this to your email address
        $subject = 'New message from your website';
        $message = 'Name: '.$_POST['fname'].' '.$_POST['lname']."\r\n".
            'Email: '.$_POST['email']."\r\n".
            'Message: '."\r\n".$_POST['message'];

        // Set up the email headers
        $headers = 'From: '.$_POST['fname'].' '.$_POST['lname'].' <'.$_POST['email'].'>'."\r\n".
            'Reply-To: '.$_POST['email']."\r\n".
            'X-Mailer: PHP/'.phpversion();

        // Send the email
        if (mail($to, $subject, $message, $headers)) {
            $success_output = 'Your message was sent successfully.'; // Success message
        } else {
            $error_output = 'Something went wrong. Please try again later'; // Error message
        }
    } else {
        $error_output = 'reCAPTCHA verification failed. Please try again later.'; // Error message
    }
} else {
    $error_output = 'Please fill out all of the required fields.'; // Error message
}

// Output error or success message
$output = [
    'error' => $error_output,
    'success' => $success_output
];

// Return the output in JSON format
echo json_encode($output);

init.js 文件附加到此 pastebin:

https://pastebin.com/Kkgnmmr0

我已经将我的 nginx 配置为接受 POST 请求,并且我的 php.ini 文件配置了 postsend 并允许 mail()

代码:

sendmail_path = /usr/sbin/sendmail -t -i -f [email protected]

出于隐私原因删除了电子邮件地址

提前感谢您的帮助!

我希望 init.js 文件对表单字段进行错误检查,然后 send.php 将包含表单详细信息的电子邮件发送到我的电子邮件地址。

您可以在此处测试页面底部的表单: http://test.steamexchange.io/

更新的 PHP: https://pastebin.com/0G6KXRHf

更新的 NGINX 配置:

    listen 80;
    server_name steamexchange.io steamexchange.ca localhost;
    root /var/www/html/;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        root /var/www/html/;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    # Recaptcha v3 configuration
    location = /send.php {
        internal;
        proxy_set_header X-Recaptcha-Secret "redacted";
        proxy_set_header X-Recaptcha-Response $http_x_recaptcha_response;
        proxy_pass_request_headers off;
        proxy_pass http://127.0.0.1:8080/send.php;
    }
}

日志错误:

(
    [success] => 
    [error-codes] => Array
        (
            [0] => invalid-input-response
        )

)" while reading response header from upstream, client: 24.150.119.162, server: test.steamexchange.io, request: "POST /send.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "test.steamexchange.io", referrer: "http://test.steamexchange.io/"
2023/03/09 02:41:19 [error] 374627#374627: *5 FastCGI sent in stderr: "PHP message: stdClass Object
(
    [success] => 
    [error-codes] => Array
        (
            [0] => invalid-input-response
        )

)" while reading response header from upstream, client: 24.150.119.162, server: test.steamexchange.io, request: "POST /send.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "test.steamexchange.io", referrer: "http://test.steamexchange.io/"
javascript php html recaptcha
© www.soinside.com 2019 - 2024. All rights reserved.