Ошибка google recaptcha в codeigniter php при отправке формы - PullRequest
0 голосов
/ 30 мая 2020

Я создал форму в codeigniter и присвоил google captcha v2, я создал ключ сайта, и секретный ключ добавил его в файлы конфигурации, а также добавил js и div recaptcha, включая мой ключ сайта. вот моя функция captcha в контроллере:

public function validate_captcha() {
          $recaptcha = trim($this->input->post('g-recaptcha-response'));
          $userIp= $this->input->ip_address();
          $secret='xxxxxxxxxxxx'; (i have given my scret key here)
          $secretdata = array(
              'secret' => "$secret",
              'response' => "$recaptcha",
              'remoteip' =>"$userIp"
          );

          $verify = curl_init();
          curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
          curl_setopt($verify, CURLOPT_POST, true);
          curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($secretdata));
          curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
          curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($verify);
          $status= json_decode($response, true);
          if(empty($status['success'])){
              return FALSE;
          }else{
              return TRUE;
          }
      }

следующая моя функция формы регистра в том же контроллере:

public function ajaxRegAction() {
			$this->load->library('session');
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
		header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
		$this->load->library('form_validation');
		$utype='W';
    $dhamu = $this->validate_captcha();
		$createddate  = date('Y-m-d h:i:s');
		$createdby = '0';
		$mobile = $this->input->post('phone');
		$form_data = array(
				'type' => $utype,
				'unique_id' => $this->mainModel->generateIndividualID(),
				'phone_num' => $mobile,
				'email' => $this->input->post('email'),
				'first_name' => $this->input->post('firstname'),
				'last_name' => $this->input->post('lastname'),
				'created_by' => $createdby,
				'created_date' => $createddate,
		);
		$name = $this->input->post('firstname')." ".$this->input->post('lastname');
		$access_info = array('user_type'=>$utype);

			$check = $this->mainModel->checkUserAvail($this->input->post('phone'),$this->input->post('email'));
			$checkauser = $this->mainModel->checkAjaxUser($this->input->post('phone'),$this->input->post('email'));
			if($check==0) {

        if($dhamu==1){

				$insert = $this->mainModel->ajaxRegInsertUser($form_data, $access_info,$this->input->post('password'));

				$message="Dear ".$this->input->post('firstname').", You have successfully registered with Book The Party. Thank You for coming On-Board. Contact us at 9666888000 for any queries - Team BTP";
				$email_message=$message;
				$message=rawurlencode($message);
				$this->mainModel->sendOtptoCustomer($mobile,$message);
				$this->mainModel->sendmailtoCustomer($this->input->post('email'),$email_message);

echo "success";
}

else{ echo "Captcha Error";}



}

else{
echo "Registration Failed !";

			}

даже если я поставлю флажок в поле google recaptcha и нажму «регистр», форма покажет «Ошибка Captcha», значения также не добавляются в базу данных. может кто-нибудь подскажите, пожалуйста, что здесь может быть не так, заранее спасибо

1 Ответ

0 голосов
/ 30 мая 2020

Шаг 1. Убедитесь, что вы добавили localhost в свой домен на панели инструментов Google Captcha V2.

Шаг 2:

Я изменяю вашу функцию, вы можете использовать ее следующим образом:

public function validate_captcha() 
{
    if(isset($_POST['g-recaptcha-response']))
    {
        $captcha=$_POST['g-recaptcha-response'];
    }

    $secretKey = "Put your secret key here";
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response,true);
    // should return JSON with success as true
    if($responseKeys["success"]) {
        return TRUE;
    } else {
        return FALSE;
    }
}

вместо CURL

Сообщите мне, работает ли это

...