Validate recaptcha ajax and codeigniter

烈酒焚心 提交于 2019-12-11 16:58:34

问题


I am using Codeigniter and Ajax to validate and submit the email form. I tried many methods, it keeps giving me the result {"sent":false} it was working great before I add the recaptcha lines.

here is my code:

custom.script.js

$("#ajax-contact-form").submit(function() {
    var href = 'http://localhost:8888/en/send';
    var name = $("#form-name").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    var title = $("#form-title").val();
    var message = $("#form-message").val();
    $.ajax({
        type: "POST",
        url: href ,
        dataType: "json",
        data: {
            name: name,
            email: email,
            phone: phone,
            title: title,
            message: message,
            //UPDATE from recaptcha without quotes to 'g-recaptcha-response'
            'g-recaptcha-response': grecaptcha.getResponse()
          },

        success: function(msg) {
            if(msg.sent) {
                console.log("Successssssssssss");
                $('#result').addClass('success'); 
                $('#result').html('Email was sent successfully!');
            } else {
                $('#result').addClass('error'); 
                $('#result').html('Email was NOT sent!'); 
            }
        }
    });
    return false;
});

En.php

function send()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $google_url="https://www.google.com/recaptcha/api/siteverify";
    //UPDATE from recaptcha to 'g-recaptcha-response'
    $str = $this->input->post('g-recaptcha-response');
    $secret = 'GOOGLE_SECRET_KEY';
    $url=$google_url."?secret=".$secret."&response=".$str;
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $output = curl_exec($ch); 
    curl_close($ch);      
    $status= json_decode($output, true);


    if ($status['success']) {


    $this->load->library('email');

    $config['mailtype'] = 'html';
    $config['charset'] = 'utf-8';
    $config['wordwrap'] = TRUE;

    $this->email->initialize($config);

    $body    = 'ANY TEXT';
    $emailto = "email@domain.com";

    $this->email->from($this->input->post("email"), $this->input->post("name"));
    $this->email->to($emailto);
    $this->email->subject('New Request');
    $this->email->message($body);

    if($this->email->send()){
    echo json_encode(array("sent"=>TRUE));
    }

}
else{
    echo json_encode(array("sent"=>FALSE));
}}

The google keys are correct, I don't know why it is not getting to the true if statement.


回答1:


Hello let's discuss this. It seems that returned data $status['success'] needs to compare with a required values using "==" operator. You can check it like this.

if ($status['success'] == true) {


$this->load->library('email');

$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;

$this->email->initialize($config);

$body    = 'ANY TEXT';
$emailto = "email@domain.com";

$this->email->from($this->input->post("email"), $this->input->post("name"));
$this->email->to($emailto);
$this->email->subject('New Request');
$this->email->message($body);

if($this->email->send()){
echo json_encode(array("sent"=>TRUE));
}

}

Also please distinguish the values before putting it on condition (if else statement).




回答2:


It finally worked this is the final code:

function send()
{
    $this->load->helper('form');
    $this->load->library('form_validation');


$google_url="https://www.google.com/recaptcha/api/siteverify";
$str = $this->input->post('g-recaptcha-response');



$secret = 'GOOGLE SECRET KEY';
$url=$google_url."?secret=".$secret."&response=".$str;


$response = json_decode(file_get_contents($url), true);
if ($response["success"] != false) {




    $this->load->library('email');

    $config['mailtype'] = 'html';
    $config['charset'] = 'utf-8';
    $config['wordwrap'] = TRUE;

    $this->email->initialize($config);

    $body    = 'ANY TEXT';

    $emailto = "email@domain.com";

    $this->email->from($this->input->post("email"), $this->input->post("name"));
    $this->email->to($emailto);

    $this->email->subject('New Request');
    $this->email->message($body);

    if($this->email->send()){
    echo json_encode(array("sent"=>TRUE));
    }
}
    else{
    echo json_encode(array("sent"=>FALSE));
     }
    }



回答3:


If you use 'g-recaptcha-response' and $status['success'] returns null in your given implementation, it might be better to use the method of cURL request as below:

$google_url = "https://www.google.com/recaptcha/api/siteverify";
$secret_key = 'YOUR_SECRET_KEY';

$response = $_POST['g-recaptcha-response']; 

$message  = 'Google reCaptcha Test';

if(!empty($response))
{
    $url = $google_url."?secret=".$secret_key."&response=".$response;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_TIMEOUT, 15);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE); 
    $curlData = curl_exec($curl);

    curl_close($curl);

    $res = json_decode($curlData, TRUE);
    if($res['success'] == 'true') 
        $message = "Success!";
    else
        $message = "Enter captcha again!";
}


来源:https://stackoverflow.com/questions/54297861/validate-recaptcha-ajax-and-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!