简体   繁体   English

带有reCaptcha v2的PHP和AJAX表单无法运行PHP脚本

[英]PHP and AJAX form with reCaptcha v2 fails to run the PHP script

I'm currently making a personal website from scratch using a webserver running Apache and PHP 5.6. 我目前正在使用运行Apache和PHP 5.6的网络服务器从头开始创建个人网站。 I made the framework, some pages, and some CSS. 我制作了框架,一些页面和一些CSS。 I'm currently having issues integrating Google's reCaptcha v2 to my contact form. 我目前在将Google的reCaptcha v2集成到我的联系表时遇到问题。 I was able to integrate it into the form through the HTML and my AJAX script is working correctly, but I can't for the life of me figure out how to properly integrate the captcha check into my PHP script. 我能够通过HTML将其集成到表单中,并且我的AJAX脚本可以正常工作,但是我一辈子都无法弄清楚如何将验证码检查正确集成到我的PHP脚本中。 I want to like PHP, and I'm going to have to use it more, but It's been extremely frustrating to try and get this working. 我想喜欢PHP,而且我将不得不更多地使用它,但是尝试使其正常运行却非常令人沮丧。

This form works perfectly without the catcha integration, but when I introduce the changes tot he PHP script, it fails to complete and form messages don't get sent. 这种形式在没有catcha集成的情况下可以完美地工作,但是当我向PHP脚本介绍更改时,它无法完成,并且表单消息也不会发送。 I've been tracking down the exact issue, but can't figure it out. 我一直在寻找确切的问题,但无法解决。 I would love to use JS alert() to stub different parts of the script, but since it's PHP I can't do that :c I also used a few validators to make sure that the PHP's syntax was correct. 我很想使用JS alert()对脚本的不同部分进行存根,但是由于它是PHP,所以我无法做到这一点:c我还使用了一些验证器来确保PHP的语法正确。 There are no errors in my IDE. 我的IDE中没有错误。

Can anybody see any absurd issues with the following PHP form script? 使用以下PHP表单脚本,谁能看到任何荒谬的问题?

PHP 的PHP

 <?php // Only process POST reqeusts. if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) { // Get the form fields and remove whitespace. $firstname = strip_tags( trim( $_POST[ "firstname" ] ) ); $firstname = str_replace( array( "\\r", "\\n" ), array( " ", " " ), $firstname ); $lastname = strip_tags( trim( $_POST[ "lastname" ] ) ); $lastname = str_replace( array( "\\r", "\\n" ), array( " ", " " ), $lastname ); $email = filter_var( trim( $_POST[ "email" ] ), FILTER_SANITIZE_EMAIL ); $phone = filter_var( trim( $_POST[ "phone" ] ), FILTER_SANITIZE_NUMBER_INT ); $message = trim( $_POST[ "message" ] ); $validation = false; function buildCaptchaUrl() { $captcha = $_POST[ 'g-recaptcha-response' ]; $secret = 'SECRET'; return "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=" . $captcha . "&remoteip=" . $_SERVER[ 'REMOTE_ADDR' ]; } function fileGetContentsCurl( $url ) { $ch = curl_init(); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_HEADER, 0 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); $data = curl_exec( $ch ); curl_close( $ch ); return $data; } function sendCaptchaResponse() { $response = json_decode( file_get_contents_curl( buildCaptchaUrl() ), true ); if ( $response[ 'success' ] == false ) { return false; } return true; } //The problematic chain of events is caused by this $validation = sendCaptchaResponse(); if ( $validation == false ) { //captcha failed http_response_code( 403 ); echo "Please verify your humanity by using the captcha."; exit; } else if ( $validation == true ) { //captcha passed // Check that data was sent to the mailer. if ( empty( $firstname )OR empty( $message )OR!filter_var( $email, FILTER_VALIDATE_EMAIL ) ) { // Set a 400 (bad request) response code and exit. http_response_code( 400 ); echo "Some form fields must have been empty. Please complete the form and submit again."; exit; } // Set the recipient email address. // FIXME: Update this to your desired email address. $recipient = "chris@chillstice.com"; // Set the email subject. $subject = "Form Submission by $firstname $lastname"; // Build the email content. $email_content = "Name: $firstname $lastname\\n"; $email_content .= "Email: $email\\n"; $email_content .= "Phone: $phone\\n\\n"; $email_content .= "Message:\\n$message\\n"; // Build the email headers. $email_headers = "From: $firstname $lastname <$email>"; // Send the email. if ( mail( $recipient, $subject, $email_content, $email_headers ) ) { // Set a 200 (okay) response code. http_response_code( 200 ); echo "Your message has been sent and I will be in contact soon."; } else { // Set a 500 (internal server error) response code. http_response_code( 500 ); echo "Something went wrong and we couldn't send your message."; } } } else { // Not a POST request, set a 403 (forbidden) response code. http_response_code( 403 ); echo "There was a problem with your submission, please try again."; } ?> 

HTML 的HTML

 <form id="form" class="item needs-validation" method="POST" action="contact-form.php" novalidate> <div class="form-row"> <div class="form-group col-md-6"> <label for="firstname">First name *</label> <input id="firstname" name="firstname" class="form-control" placeholder="John" type="text" required maxlength="100"> <div class="valid-feedback">What a lovely name!</div> <div class="invalid-feedback">That's no name.</div> </div> <div class="form-group col-md-6"> <label for="lastname">Last name *</label> <input id="lastname" name="lastname" class="form-control" placeholder="Doe" type="text" required maxlength="100"> <div class="valid-feedback">Looks good!</div> <div class="invalid-feedback">That's not a real name.</div> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="email"><i class="far fa-envelope mr-2"></i>Email *</label> <input id="email" name="email" class="form-control" placeholder="someone@domain.com" type="email" required maxlength="100"> <div class="valid-feedback">Valid</div> <div class="invalid-feedback">That's not a real email...</div> </div> <div class="form-group col-md-6"> <label for="phone"><i class="fas fa-mobile-alt mr-2"></i>Phone</label> <input id="phone" name="phone" class="form-control" placeholder="1234567890" type="tel" maxlength="20"> <div class="valid-feedback">Not required.</div> <div class="invalid-feedback">That's not a real phone number.</div> </div> </div> <div class="form-row"> <div class="form-group col-12"> <label for="message"><i class="fa fa-comment-alt mr-2"></i>Message *</label> <textarea id="message" name="message" class="form-control" placeholder="" maxlength="100000"></textarea> <div class="valid-feedback">Nice message.</div> <div class="invalid-feedback">I have no idea what you did, but that's not valid.</div> </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <div class="g-recaptcha" data-sitekey="6LdOqVsUAAAAAN25grBs05Ip8JmjGQNqURivfH0y"></div> </div> <div class="form-group col-md-6"> <button id="submit" name="submit" type="submit" class="btn btn-primary btn-lg" style="float: right;"> Submit </button> </div> </div> </form> 

JS AJAX JS AJAX

 $(function() { "use strict"; // Get the form. var form = $('#form'); // 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) { // Set the message text. $('#alert-form-success-text').text(response); $('#alert-form-success').css({ "visibility": "visible", "opacity": "1" }); $('#alert-form-fail').css({ "visibility": "hidden", "opacity": "0" }); }) .fail(function(data) { $('#alert-form-fail').css({ "visibility": "visible", "opacity": "1" }); $('#alert-form-success').css({ "visibility": "hidden", "opacity": "0" }); // Set the message text. if (data.responseText !== '') { $('#alert-form-fail-text').text(data.responseText); } else { $('#alert-form-fail-text').text('An internal error occured and your message could not be sent.'); } }); }); }); 

The issue only relates to the reCaptcha integration, the scripts ability to get the POST information and email is fine. 该问题仅与reCaptcha集成有关,脚本获得POST信息和电子邮件的功能很好。 I think the issue is localized to the chain of methods started by 我认为问题仅限于由

$validation = sendCaptchaResponse();

If you have any questions, don't hesitate to ask. 如有任何疑问,请随时提出。 Here's the page with the form: https://chillstice.com/contact 这是具有以下格式的页面: https : //chillstice.com/contact

The fileGetContentsCurl() function in the PHP file was being run as 'file_get_contents_curl()' PHP文件中的fileGetContentsCurl()函数以“ file_get_contents_curl()”运行

Fixing this typo and making the methods go by a consistent name solved this issue. 解决此错字并使用一致的名称命名方法可以解决此问题。 I sure wish my IDE or the debugging tools would have helped me fix this one (1) typo, but that's PHP for you. 我当然希望我的IDE或调试工具能够帮助我解决这一(1)错字,但是那是适合您的PHP。

I would like to thank Karlo Kokkak for alluding me to the typo. 我要感谢Karlo Kokkak提到我的错字。

After making the changes, the entire script works as intended. 进行更改后,整个脚本将按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM