반응형
AJAX를 사용한 ReCaptcha 2.0
제 웹사이트에서 리캡차 2.0을 작동시킬 수 있었습니다.다만, AJAX를 사용하지 않고, 「자연스럽게」 폼을 송신할 때만 동작합니다.
captcha와 함께 폼을 제출하고 페이지를 새로 고치지 않고 성공 노트로 사용자에게 알리고 싶습니다.
다음 코드를 시도했지만 서버가 사용자 응답을 받지 못하는 것 같습니다.
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
@mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
PHP 페이지의 결과는 다음과 같습니다.
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
요컨대, POST 데이터의 나머지 부분과 자동으로 일치하지 않고 수동으로 입력 응답을 얻을 수 있는 방법은 무엇입니까?
좋아, 이건 꽤 바보같은 짓이었어
제가 몇 가지 잘못을 저질렀습니다.
- PHP 파일에서는 모든 문자열에 작은 따옴표가 붙어 있어 문제가 발생하였습니다.
- 테스트를 통해 PHP 파일에 여러 개의 인쇄물을 추가했습니다. 따라서,
if (status == "ok")효과가 없었습니다.메일은 받았지만 확인은 되지 않았고, 그 이유를 알 수 있었습니다. - PHP 파일이 누락되어 있는지 확인하고 싶었을 때 URL에 있는 주소로 가면 항상 오류가 발생합니다.심지어 우편물이 발송되었을 때도.이제 로그 체크 방법이 올바르지 않다는 것을 알게 되었습니다.
@사무라이에게 도움을 주셔서 감사합니다.
최종 PHP 코드:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
@mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>
언급URL : https://stackoverflow.com/questions/30006081/recaptcha-2-0-with-ajax
반응형
'programing' 카테고리의 다른 글
| Swift [45] 디코딩 가능한 프로토콜에서 JSON 사전 유형을 사용하여 속성을 디코딩하는 방법 (0) | 2023.03.06 |
|---|---|
| Oracle SQL Developer에서 변수 대체를 피하는 방법 (0) | 2023.03.06 |
| 타임아웃과 함께 sping의 restTemplate를 사용하여 타임아웃을 검출하려면 어떻게 해야 합니까? (0) | 2023.03.06 |
| mod_pagespeed는 CSS와 JS를 결합하지 않습니다. (0) | 2023.03.06 |
| 직렬화된 양식의 데이터를 json 개체로 변환하는 중 (0) | 2023.03.06 |