@Noatitauaggi

Как сделать recaptcha в форме обязательной если стоит v2 и v3?

Приветствую всех! Надеюсь кто-нибудь сможет помочь и если нужно "на пиво", мне не жалко, т.к уже не охота жить после недельного бодания с этой штукой.
Взял из этой темы https://habr.com/ru/post/582984/ и переделал под свою форму, но заявка отправляется без прохождения капчи.
Здесь были аналогичные вопросы, но там речь шла про работу лишь с одной из версий капчи, а у меня их две.

Код формы обратной связи (взял из темы выше) и добавил лишь пользовательское соглашение и строку form редактировал.
<form action="ajax.php" id="form_vopros_expert" class="feedback col-6 offset-md-3" method="post">
<input type="checkbox" id="garant_ch_expert" checked="checked"> <label for="garant_ch_expert">Соглашаюсь на <a href="/contacts/politika-konfidentsialnosti/" target="_blank">обработку персональных данных</a></label>


Код файла feedback.js
$(document).ready(function(){
	
	$('.files').click(function(){
        $(this).closest('form').find('input[type=file]').click();
	});

    $('input[type=file]').change(function(){
        var form = $(this).closest('form');
    	var count = form.find("input:file")[0].files.length;
    	form.find('.files span').text('Выбрано '+count+' файл(ов)');
    });
	
	/* date form */
	$(function () {
		$('.datepicker').datepicker({
            closeText: 'Закрыть',
			prevText: 'Предыдущий',
            format:'d.m.Y',
			nextText: 'Следующий',
			monthNames : ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
			dayNamesMin : ['Вс','Пн','Вт','Ср','Чт','Пт','Сб']
		});
		$('.sel1 select').change(function(){
			$('.sel1 select').css({'color':'black'});
		});
		$('.sel2 select').change(function(){
			$('.sel2 select').css({'color':'black'});
		});
	});

	/* FORM EXPERT */
	
	$("#form_vopros_expert").submit(function(event){
		event.preventDefault();
		var formData = new FormData(this);
		if($('#garant_ch_expert').prop('checked')){
			$.ajax({
				url: "/lib/feedback/mail-form.php",
				type: "post",
				data: formData,
				success: function(data) {
					$("#titlepop_expert").html('<div class="thanks_form">'+data+'</div>');
				},
				error: function(){
					alert("Ваша заявка не отправлена! Попробуйте еще раз");
				},
				cache: false,
		        contentType: false,
		        processData: false
			});	
			$("#garant_error_expert").html("");
		} else {$("#garant_error_expert").html("Необходимо дать согласие");}	
	});


Код обработчика mail-form.php
<?php

    require('config.php');
	use PHPMailer\PHPMailer\PHPMailer;
	use PHPMailer\PHPMailer\Exception;
	use PHPMailer\PHPMailer\SMTP;

	require 'PHPMailer/src/Exception.php';
	require 'PHPMailer/src/PHPMailer.php';
	require 'PHPMailer/src/SMTP.php';

	$mail = new PHPMailer(true);
    

global $APPLICATION;
    
    $dlina = htmlspecialchars(stripslashes(trim($_POST['form_dlina'])));
     $shirina = htmlspecialchars(stripslashes(trim($_POST['form_shirina'])));
      $plotnost = htmlspecialchars(stripslashes(trim($_POST['form_plotnost'])));
       $obiom = htmlspecialchars(stripslashes(trim($_POST['form_obiom'])));
      
    
    $name = htmlspecialchars(stripslashes(trim($_POST['form_name'])));
	$phone = htmlspecialchars(stripslashes(trim($_POST['form_phone'])));
	$email = htmlspecialchars(stripslashes(trim($_POST['form_email'])));
    $date = htmlspecialchars(stripslashes(trim($_POST['form_date'])));
    $time = htmlspecialchars(stripslashes(trim($_POST['form_time'])));
    $work = htmlspecialchars(stripslashes(trim($_POST['form_work'])));
	$message = htmlspecialchars(stripslashes(trim($_POST['form_message'])));
	
	$tovar = htmlspecialchars(stripslashes(trim($_POST['tovar'])));
	$title = htmlspecialchars(stripslashes(trim($_POST['title'])));
  
    
    $text = '';
    
    	$text .= (!empty($tovar))?'<p><strong>tovar:</strong> '.$tovar.'</p>':'';
    $text .= (!empty($name))?'<p><strong>name:</strong> '.$name.'</p>':'';
    $text .= (!empty($phone))?'<p><strong>phone:</strong> '.$phone.'</p>':'';
	$text .= (!empty($email))?'<p><strong>email:</strong> '.$email.'</p>':'';
    $text .= (!empty($date))?'<p><strong>date:</strong> '.$date.'</p>':'';
    $text .= (!empty($time))?'<p><strong>time:</strong> '.$time.'</p>':'';
    $text .= (!empty($work))?'<p><strong>usluga:</strong> '.$work.'</p>':'';
	$text .= (!empty($message))?'<p><strong>message:</strong> '.$message.'</p>':'';
	
	$text .= (!empty($dlina))?'<p><strong>dlina/dlina namotky:</strong> '.$dlina.'</p>':'';
		$text .= (!empty($shirina))?'<p><strong>shirina:</strong> '.$shirina.'</p>':'';
			$text .= (!empty($plotnost))?'<p><strong>plotnost/tolshina:</strong> '.$plotnost.'</p>':'';
				$text .= (!empty($obiom))?'<p><strong>obiom zakupki:</strong> '.$obiom.'</p>':'';
				
    
    $text .= (!empty($title))?'<p><strong>tovar:</strong> '.$title.'</p>':'';
    $text .= (!empty($_SERVER['HTTP_REFERER']))?'<p><strong>url:</strong> '.$_SERVER['HTTP_REFERER'].'</p>':'';
	
	$mail->isSMTP();
	$mail->Host = $host;
	$mail->SMTPAuth = true;
	$mail->Username = $login;
	$mail->Password = $pass;
	$mail->SMTPSecure = 'ssl';
	$mail->Port = 465;
	 
	$mail->From = $from;
	$mail->FromName = $fromname;
	$mail->addAddress($to);
	$mail->isHTML(true);
	 
	$mail->Subject = $subject;
	$mail->Body    = $text;
	$mail->AltBody = $text;
	



	if(!empty($_FILES['files'])){
        $sizes = 0;
		foreach($_FILES['files']['name'] as $key => $val){
            $name = $_FILES['files']['name'][$key];
            $name = str_replace(' ', '_', $name);
            if($name == '') continue;
            $type = $_FILES['files']['type'][$key];
            $tmp_name = $_FILES['files']['tmp_name'][$key];
            $error = $_FILES['files']['error'][$key];
            $size = $_FILES['files']['size'][$key];

            if($error > 0){
                echo 'Произошла ошибка при загрузке файла "'.$name.'"';
				exit;
            }

			$ext = strtolower(substr($name, strpos($name,'.'), strlen($name)-1));
			if(!in_array($ext, $extensions)){
				echo 'Тип файла "'.$name.'" запрещен к загрузке';
				exit;
			}

			$sizes += $size;
			if($sizes > $maxSize){
				echo 'Суммарный объем файлов превышает 10Мб';
				exit;
			}

			$tt = explode('/',$tmp_name);
			$tt = $tt[count($tt) - 1];
			$namefile = $tt.$ext;
			$mail->addAttachment($tmp_name,$namefile);
		}
	}

	try {

	$mail->send();

	echo 'Спасибо! Ваша заявка отправлена';
	} catch (Exception $e) {
		echo 'Ваша заявка не отправлена! Попробуйте еще раз. Ошибка: ', $mail->ErrorInfo;
	}


?>
  • Вопрос задан
  • 135 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы