Пользовательская контактная форма с простой Math Captcha

У меня есть хорошо работающая контактная форма на моем сайте. Теперь я пытаюсь включить математическую капчу в. К сожалению, я не смог заставить его работать. Любая идея, как (где) включить коды капчи?

Я много чего перепробовал, но он не работает должным образом. Может быть, код не самый лучший 🙂 Я уже искал решение в stackoverflow и Google без удачи.

Моя рабочая контактная форма на данный момент:

<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = sprintf( __( 'Please enter your name.', 'test_theme' ) );
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}

if(trim($_POST['email']) === '')  {
$emailError = sprintf( __( 'Please enter your email address.', 'test_theme' ) );
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = sprintf( __( 'You entered an invalid email address.', 'test_theme' ) );
$hasError = true;
} else {
$email = trim($_POST['email']);
}

if(trim($_POST['comments']) === '') {
$commentError = sprintf( __( 'Please enter a message.', 'test_theme' ) );
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}

if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = sprintf( __( 'Contact Form', 'test_theme' ) );
$body = "Name: $name \n\nMail: $email \n\n $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}

} ?>

<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p><?php _e( 'Thanks, your email was sent successfully.', 'test_theme' ); ?></p>
</div>
<?php } else { ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error-conform"><?php _e( 'Sorry, an error occured.', 'test_theme' ); ?><p>
<?php } ?>

<form action="<?php the_permalink(); ?>" class="author-description" id="contactForm" method="post">
<h2><?php _e( 'Contact Us', 'test_theme' ); ?></h2><br />
<p><label for="contactName"><?php _e( 'Your Name', 'test_theme' ); ?> <span>*</span>
<?php if($nameError != '') { ?>
<span class="error-conform"><?=$nameError;?></span>
<?php } ?><br />
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" /></label></p>

<p><label for="email"><?php _e( 'Your Email Adress', 'test_theme' ); ?> <span>*</span>
<?php if($emailError != '') { ?>
<span class="error-conform"><?=$emailError;?></span>
<?php } ?><br />

<input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" /></label></p>

<p><label for="commentsText"><?php _e( 'Your Message', 'test_theme' ); ?> <span>*</span>
<?php if($commentError != '') { ?>
<span class="error-conform"><?=$commentError;?></span>
<?php } ?><br />
<textarea type="text" name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea></label></p>

<p><input type="submit"></p>

<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>

Код Captcha, который должен быть включен в контактную форму выше:

Часть 1:

if(!isset($_POST['submitted'])) {
session_start();
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
}

Часть 2:

    if ($_SESSION['answer'] != $_POST['answer'] ) {
$mathError = 'Please answer the math question.';
$hasError = true;
}

Часть 3:

    <span class="error-conform"><?=$mathError;?></span>
<li><label>What's <?php echo $math; ?> = </label><input name="answer" type="text" /></li>

0

Решение

Я думаю, это даст вам некоторые идеи.

<?php
session_start(); // session start should be the very first line of your php code, for session management

// checking whether the form is being submitted by the user
if( isset($_POST['submitted']) )
{
// checking whether the user submitted answer matches with the captcha
if ($_SESSION['answer'] != $_POST['answer'] )
{
$mathError = 'Please answer the math question.';
$hasError = true;
}

// ....
// do other form validations here..
// ....

if( !$hasError )
{
// no errors, so send the mail or do whatever you want to do here...
}
}

// now generating new captcha
$digit1 = mt_rand(1,6);
$digit2 = mt_rand(1,6);
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
?>
<!-- html goes here --->

<forma ction="<?php the_permalink(); ?>
<!-- include the form fields here... -->

<?php if(!empty($mathError)) { ?>
<span class="error-conform"><?php echo $mathError; ?></span>
<?php } ?>

<label>What's <?php echo $math; ?> = </label><input name="answer" type="text" />
<input type="hidden" name="submitted" id="submitted" value="true" />

</form>

<!-- rest of the html goes here --->
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector