php jquery 验证码 输入后验证表单
可以刷新验证码,提交验证是否输入正确
PHP Code
- <?php
- session_start();
- $cap = 'notEq';
- if ($_SERVER['REQUEST_METHOD'] == 'POST') {
- if ($_POST['captcha'] == $_SESSION['cap_code']) {
- // Captcha verification is Correct. Do something here!
- $cap = 'Eq';
- } else {
- // Captcha verification is wrong. Take other action
- $cap = '';
- }
- }
- ?>
- <form action="index.php" method="post">
- <div id="form">
- <table border="0" width="100%">
- <tr>
- <td colspan="2"><label>Name:</label><label class="mandat"> *</label><br/>
- <input type="text" name="name" id="name"/></td>
- </tr>
- <tr>
- <td colspan="2"><label>Message:</label><label class="mandat"> *</label><br/>
- <textarea name="msg" id="msg"></textarea></td>
- </tr>
- <tr>
- <td colspan="2"><label>Enter the contents of image</label><label class="mandat"> *</label></td>
- </tr>
- <tr>
- <td width="60px">
- <input type="text" name="captcha" id="captcha" maxlength="6" size="6"/></td>
- <td><img id="captcha-image-new" name="captcha-image-new" src="captcha.php"/>
- </td>
- </tr>
- <tr>
- <td><input type="submit" value="Submit" id="submit"/></td>
- <td><a href="#" onClick="javascript:refresh();" id="change-image">看不清,换一个</a> </td>
- </tr>
- </table>
- </div>
- </form>
- <div class="cap_status"></div>
- </div>
js文件
JavaScript Code
- <script type="text/javascript">
- $(document).ready(function(){
- $('#submit').click(function(){
- var name = $('#name').val();
- var msg = $('#msg').val();
- var captcha = $('#captcha').val();
- if( name.length == 0){
- $('#name').addClass('error');
- }
- else{
- $('#name').removeClass('error');
- }
- if( msg.length == 0){
- $('#msg').addClass('error');
- }
- else{
- $('#msg').removeClass('error');
- }
- if( captcha.length == 0){
- $('#captcha').addClass('error');
- }
- else{
- $('#captcha').removeClass('error');
- }
- if(name.length != 0 && msg.length != 0 && captcha.length != 0){
- return true;
- }
- return false;
- });
- var capch = '<?php echo $cap; ?>';
- if(capch != 'notEq'){
- if(capch == 'Eq'){
- $('.cap_status').html("Your form is successfully Submitted ").fadeIn('slow').delay(3000).fadeOut('slow');
- }else{
- $('.cap_status').html("Human verification Wrong!").addClass('cap_status_error').fadeIn('slow');
- }
- }
- });
- function refresh()
- {
- document.getElementById('captcha-image-new').src='captcha.php?'+Math.random();
- document.getElementById('captcha').focus();
- }
- </script>
captcha.php
PHP Code
- <?php
- session_start();
- $ranStr = md5(microtime());
- $ranStr = substr($ranStr, 0, 6);
- $_SESSION['cap_code'] = $ranStr;
- $newImage = imagecreatefromjpeg("cap_bg.jpg");
- $txtColor = imagecolorallocate($newImage, 0, 0, 0);
- imagestring($newImage, 5, 5, 5, $ranStr, $txtColor);
- header("Content-type: image/jpeg");
- imagejpeg($newImage);
- ?>
原文地址:http://www.freejs.net/article_biaodan_65.html