在联系表格提交之前输入Captcha PHP&使用Javascript

时间:2014-12-01 00:35:37

标签: javascript php forms captcha

我有一个联系表格,如果用户需要帮助,可以与我联系。问题是我无法使验证码工作。

contact_form.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form</title>
<meta name="keywords" content="" /> 
<meta name="description" content="" /> 
<link href="tooplate_style.css" rel="stylesheet" type="text/css" />
    <script  src="js/jquery.min.js"></script>
</head>
<div id="tooplate_wrapper">

    <div id="tooplate_header">

        <div id="site_title"><h1><a href="http://deathsrepo.pw">Technologx</a></h1></div>         
        <div id="twitter"><a href="https://twitter.com/Technologx" target="_blank"></a></div>

        <div id="facebook"><a href="https://facebook.com/Technologx2013" target="_blank"></a></div>

        <div id="tooplate_menu">
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="http://deathsrepo.pw/themes.php">Themes</a></li>
                <li><a href="http://blog.deathsrepo.pw">Blog</a></li>
                <li><a href="http://deathsrepo.pw/store.php">Store</a></li>
                <li class="last"></li>
                <li><a href="http://deathsrepo.pw/contact_form.php" class="current">Contact Us</a></li>
                <li class="last"></li>
            </ul>       
        </div> <!-- end of tooplate_menu -->
<style>


body, div, h1,h2, form, fieldset, input, textarea, footer,p {
    margin: 0; padding: 0; border: 0; outline: none;
}


@font-face {
    font-family: 'YanoneKaffeesatzRegular';
    src: url('fonts/yanonekaffeesatz-regular-webfont.eot');
    src: url('fonts/yanonekaffeesatz-regular-webfont.eot?#iefix') format('embedded-opentype'),
    url('fonts/yanonekaffeesatz-regular-webfont.woff') format('woff'),
    url('fonts/yanonekaffeesatz-regular-webfont.ttf') format('truetype'),
    url('fonts/yanonekaffeesatz-regular-webfont.svg#YanoneKaffeesatzRegular') format('svg');
    font-weight: normal;
    font-style: normal;
}

body { font-family: 'YanoneKaffeesatzRegular';}
p {text-shadow:0 1px 0 #fff; font-size:24px;}
#wrap {width:530px; margin:20px auto 0; height:1000px;}
h1 {margin-bottom:20px; text-align:center;font-size:48px; text-shadow:0 1px 0 #ede8d9; }


    #form_wrap { overflow:hidden; height:446px; position:relative; top:0px;
        -webkit-transition: all 1s ease-in-out .3s;
        -moz-transition: all 1s ease-in-out .3s;
        -o-transition: all 1s ease-in-out .3s;
        transition: all 1s ease-in-out .3s;}

    #form_wrap:before {content:"";
        position:absolute;
        bottom:128px;left:0px;
        background:url('images/before.png');
        width:530px;height: 316px;}

    #form_wrap:after {content:"";position:absolute;
        bottom:0px;left:0;
        background:url('images/after.png');
        width:530px;height: 260px; }

    #form_wrap.hide:after, #form_wrap.hide:before {display:none; }
    #form_wrap:hover {height:776px;top:-200px;}


    form {background:#f7f2ec url('images/letter_bg.png'); 
        position:relative;top:200px;overflow:hidden;
        height:200px;width:400px;margin:0px auto;padding:20px; 
        border: 1px solid #fff;
        border-radius: 3px; 
        -moz-border-radius: 3px; -webkit-border-radius: 3px;
        box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff;
        -moz-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 14px #fff;
        -webkit-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff;
        -webkit-transition: all 1s ease-in-out .3s;
        -moz-transition: all 1s ease-in-out .3s;
        -o-transition: all 1s ease-in-out .3s;
        transition: all 1s ease-in-out .3s;}


        #form_wrap:hover form {height:530px;}

        label {
            margin: 11px 20px 0 0; 
            font-size: 16px; color: #b3aba1;
            text-transform: uppercase; 
            text-shadow: 0px 1px 0px #fff;
        }

        input[type=text], textarea {
            font: 14px normal normal uppercase helvetica, arial, serif;
            color: #7c7873;background:none;
            width: 380px; height: 36px; padding: 0px 10px; margin: 0 0 10px 0;
            border:1px solid #f8f5f1;
            -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;
            -moz-box-shadow: inset 0px 0px 1px #726959;
            -webkit-box-shadow:  inset 0px 0px 1px #b3a895; 
            box-shadow:  inset 0px 0px 1px #b3a895;
        }   

        textarea { height: 80px; padding-top:14px;}

        textarea:focus, input[type=text]:focus {background:rgba(255,255,255,.35);}

        #form_wrap input[type=submit] {
            position:relative;font-family: 'YanoneKaffeesatzRegular'; 
            font-size:24px; color: #7c7873;text-shadow:0 1px 0 #fff;
            width:100%; text-align:center;opacity:0;
            background:none;
            cursor: pointer;
            -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; 
            -webkit-transition: opacity .6s ease-in-out 0s;
            -moz-transition: opacity .6s ease-in-out 0s;
            -o-transition: opacity .6s ease-in-out 0s;
            transition: opacity .6s ease-in-out 0s;
        }

        #form_wrap:hover input[type=submit] {z-index:1;opacity:1;
            -webkit-transition: opacity .5s ease-in-out 1.3s;
            -moz-transition: opacity .5s ease-in-out 1.3s;
            -o-transition: opacity .5s ease-in-out 1.3s;
            transition: opacity .5s ease-in-out 1.3s;}

            #form_wrap:hover input:hover[type=submit] {color:#435c70;}

</style>
<body><br /><br /><br /><br />
    <div id="wrap">
        <h1>Contact Form</h1>
        <div id='form_wrap'>
            <form method="post" action="php/send.php" onsubmit="return checkForm(this);>
                <p>Hello Guest,</p>
                <label for="email">Your Message : </label>
                <textarea  name="message" value="Your Message" id="message" ></textarea>    
                <label for="name">Name: </label>
                <input type="text" name="name" value="" id="name" />
                <label for="email">Email: </label>
                <input type="text" name="email" value="" id="email" />            
<img src="php/captcha.php" width="120" height="50" border="1" alt="CAPTCHA">
<input type="text" size="6" maxlength="5" name="captcha" value="" />
                <input type="submit" name ="submit" value="Send"/>
            </form>
                    <script type="text/javascript"> 
    function checkForm(form) { if(!form.captcha.value.match(/^\d{5}$/)) { alert('Please enter the CAPTCHA digits in the box provided'); form.captcha.focus(); return false; } return true; } </script>
        </div>
    </div>
</body>
</html>

captcha.php:

<?PHP
$image = @imagecreatetruecolor(160, 45) or die("Cannot Initialize new GD image stream");
$background = imagecolorallocate($image, 0x66, 0xCC, 0xFF); 
imagefill($image, 0, 0, $background); 
$linecolor = imagecolorallocate($image, 0x33, 0x99, 0xCC); 
$textcolor1 = imagecolorallocate($image, 0x00, 0x00, 0x00); 
$textcolor2 = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
for($i=0; $i < 8; $i++) { imagesetthickness($image, rand(1,3)); imageline($image, rand(0,160), 0, rand(0,160), 45, $linecolor); } 

session_start();
$fonts = array(); 
$fonts[] = "../fonts/Courier New.ttf"; 
$fonts[] = "../fonts/Courier New Italic.ttf"; 
$fonts[] = "../fonts/Courier New Bold.ttf";
$digit = ''; for($x = 10; $x <= 130; $x += 30) { $textcolor = (rand() % 2) ? $textcolor1 : $textcolor2; $digit .= ($num = rand(0, 9)); imagettftext($image, 20, rand(-30,30), $x, rand(20, 42), 
$textcolor, $fonts[array_rand($fonts)], $num); }
 $_SESSION['digit'] = $digit;
 header('Content-type: image/png'); 
 imagepng($image); imagedestroy($image);
 ?>

我希望验证码部分能够正常工作,因为过去当我有一个联系论坛时,我让人们发送的东西只是与我们被问到的问题无关的废话。这也是为了阻止垃圾邮件机器人。如果你想看看现场版本,看看会发生什么,你可以这样做here。所有这一切都是我可以输入信息并按提交,甚至不输入验证码。

1 个答案:

答案 0 :(得分:0)

选项1(JSON)

send.php

<?php 
session_start();
if (!empty($_POST['contact'])) {
    $errors = array();
    // verify form
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }
    // ... etc..

    if (empty($_POST['captcha']) || $_SESSION['digit'] != $_POST['captcha']) {
        $errors[] = "Invalid Verification Code.";
    }
    if (!empty($errors)) {
        $errorStr = "The current request did not complete successfully...\n\n";
        $errorStr .= "- " . implode("\n- ", $errors);

        $res_arr = array('statusNum' => 2, 'message' => $errorStr);
        echo json_encode($res_arr);
    } else {
        // send email
        $res_arr = array('statusNum' => 1, 'message' => "Thank you!");
        echo json_encode($res_arr);
    }
    exit;
}
?>

contact_form.php

<form method="post" action="php/send.php" id="contactForm">
  <p>Hello Guest,</p>
  <label for="message">Your Message:</label>
  <textarea name="message" id="message"></textarea>
  <label for="name">Name:</label>
  <input type="text" name="name" value="" id="name" />
  <label for="email">Email:</label>
  <input type="text" name="email" value="" id="email" />
  <img src="php/captcha.php" width="120" height="50" border="1" alt="CAPTCHA" id="captcha_image">
  <input type="text" size="6" maxlength="5" name="captcha" value="" />
  <input type="submit" name="submit" value="Send" id="submitbutton" />
  <input type="reset" name="reset" id="resetbutton" value="Reset" style="visibility: hidden;" />
  <input type="hidden" name="contact" value="1" />
</form>
<script type="text/javascript">
var inProcess_contact = 0;
$('#contactForm').submit(function(e) {
    e.preventDefault();

    if (inProcess_contact == 0) {
        inProcess_contact = 1;
        $.ajax({
            type: 'POST',
            dataType: "json",
            url: $('form#contactForm').attr('action'),
            data: $('form#contactForm').serialize(),
            beforeSend: function() {
                $('#contactForm #submitbutton').val('Please wait...');
            },
            success: function (data) {
                $('#contactForm #submitbutton').val('Send');
                if (data.statusNum == 1) {
                    $('#contactForm #resetbutton').click();
                }
                inProcess_contact = 0;
                var d = new Date();
                $("#captcha_image").attr("src", "php/captcha.php?"+d.getTime());
                alert(data.message);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('#contactForm #submitbutton').val('Send');
                inProcess_contact = 0;
                var d = new Date();
                $("#captcha_image").attr("src", "php/captcha.php?"+d.getTime());
                alert(textStatus + ": " + errorThrown);
            },
            cache: false
        });
    }
});
</script>

选项2(HTML)

send.php

<?php 
// never forget to start the session
session_start();

$errors = "";
if(isset($_POST['submit']))
{
  if(empty($_SESSION['6_letters_code'] ) ||
    strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
  {
      //Note: the captcha code is compared case insensitively.
      //if you want case sensitive match, update the check above to
      // strcmp()
    $errors .= "n The captcha code does not match!";
  }

  if(empty($errors))
  {
    //send the email
    $to = $your_email;
    $subject="Help Needed";
    $from = $your_email;
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

    $body = "A user  $name submitted the contact form: \n".
    "Name: $name \n".
    "Email: $email \n".
    "Message: $message \n".
    "$user_message \n";

    $headers = "From: $from rn";
    $headers .= "Reply-To: $visitor_email rn";

    if (mail($to, $subject, $body, $headers)) {
        echo "ok";
    } else {
        echo "Coudn't send email. Please try again.";
    }
    //header('Location: submitted.php');
  } else {
      echo $errors;
  }
  exit;
}
?>

contact_form.php

<div id="result"></div>
<form method="post" action="php/send.php" id="contactForm">
  <p>Hello Guest,</p>
  <label for="message">Your Message:</label>
  <textarea name="message" id="message"></textarea>
  <label for="name">Name:</label>
  <input type="text" name="name" value="" id="name" />
  <label for="email">Email:</label>
  <input type="text" name="email" value="" id="email" />
  <img src="php/captcha.php" width="120" height="50" border="1" alt="CAPTCHA" id="captcha_image">
  <input type="text" size="6" maxlength="5" name="6_letters_code" value="" />
  <input type="submit" name="submit" value="Send" id="submitbutton" />
  <input type="reset" name="reset" id="resetbutton" value="Reset" style="visibility: hidden;" />
  <input type="hidden" name="contact" value="1" />
</form>
<script type="text/javascript">
var inProcess_contact = 0;
$('#contactForm').submit(function(e) {
    e.preventDefault();

    if (inProcess_contact == 0) {
        inProcess_contact = 1;
        $.ajax({
            type: 'POST',
            dataType: "html",
            url: $('form#contactForm').attr('action'),
            data: $('form#contactForm').serialize(),
            beforeSend: function() {
                $('#contactForm #submitbutton').val('Please wait...');
            },
            success: function (data) {
                if (data == 'ok') {
                    $('#contactForm #resetbutton').click();
                    $("#result").html('Request Succeeded');
                    // redirect after 3 seconds
                    setTimeout(function() {window.location = 'submitted.php';}, 3000);
                } else {
                    inProcess_contact = 0;
                    $('#contactForm #submitbutton').val('Send');
                    var d = new Date();
                    $("#captcha_image").attr("src", "php/captcha.php?"+d.getTime());
                    //alert(data.message);
                    $("#result").html(data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('#contactForm #submitbutton').val('Send');
                inProcess_contact = 0;
                var d = new Date();
                $("#captcha_image").attr("src", "php/captcha.php?"+d.getTime());
                //alert(textStatus + ": " + errorThrown);
                $("#result").html(textStatus + ": " + errorThrown);
            },
            cache: false
        });
    }
});
</script>
相关问题