最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Validating this image captcha code. Jquery PHP & javascript - Stack Overflow

programmeradmin6浏览0评论

I have the captcha creating an image in captcha.php. On my contact php page, it calls for the image & it has a reload and everything works. I just can't seem to find a way to validate it.

Here is the code that creates the captcha image:

<?php
session_start();

$word_1 = '';
$word_2 = '';

for ($i = 0; $i < 4; $i++) 
{
    $word_1 .= chr(rand(97, 122));
}
for ($i = 0; $i < 4; $i++) 
{
    $word_2 .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $word_1.' '.$word_2;

$dir = '/addons/fonts/';

$image = imagecreatetruecolor(165, 50);

$font = "recaptchaFont.ttf"; // font style

$color = imagecolorallocate($image, 0, 0, 0);// color

$white = imagecolorallocate($image, 255, 255, 255); // background color white

imagefilledrectangle($image, 0,0, 709, 99, $white);

imagettftext ($image, 22, 0, 5, 30, $color, $dir.$font, $_SESSION['random_number']);

header("Content-type: image/png");

imagepng($image); 

?>

That is all that is in that file.

Next there is the code from my actual form (contact us page):

<form id="contactForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr>
    <td><span class="greyText">Enter text shown:</span></td>
    <td>
        <div id="captcha-wrap">
            <div class="captcha-box">
                <img src="captcha.php" alt="" id="captcha" />
            </div>
            <div class="text-box">
                <label>Type the two words:</label>
                <input name="captcha-code" type="text" id="captcha-code">
            </div>
            <div class="captcha-action">
                <img src="./images/captcha-refresh.png"  alt="" id="captcha-refresh" />
            </div>
        </div>
        <span id="captchaInfo">*</span>  
    </td>
</tr>
<tr>
    <td colspan="2">
            <div class="seperator">&nbsp;</div>

            <input type="submit" name="submit" class="styleButton" style="float:right;margin-right:10px" value="SUBMIT" /></td>
</tr>
</table>
</form>

I have other rows in that table for name, email etc, but I just removed it to make this shorter.

& in the document ready function for the contact page, I have this code to refresh the captcha when button is clicked:

 // refresh captcha
 $('img#captcha-refresh').click(function() {  

        change_captcha();
 });

 function change_captcha()
 {
    document.getElementById('captcha').src='jquery-captcha.php?rnd=' + Math.random();
 }

Next is the validation I have for the whole form itself. It works for everything but the captcha:

$(document).ready(function(){
    //global vars
    var form = $("#contactForm");
    var name = $("#name");
    var nameInfo = $("#nameInfo");
    var telephone = $("#telephone");
    var telephoneInfo = $("#telephoneInfo");
    var email = $("#email");
    var emailInfo = $("#emailInfo");
    var message = $("#message");
    var messageInfo = $("#messageInfo");
    var captcha = $("#captcha-code");
    var captchaInfo = $("#captchaInfo");

    //On blur
    name.blur(validateName);
    telephone.blur(validatePhone);
    email.blur(validateEmail);
    message.blur(validateMessage);
    captcha.blur(validateCaptcha);
    //On key press
    name.keyup(validateName);
    telephone.keyup(validatePhone);
    message.keyup(validateMessage);
    captcha.keyup(validateCaptcha);
    //On Submitting
    form.submit(function(){
        if(validateName() & validateEmail() & validatePhone() & validateMessage() & validateCaptcha())
            return true
        else
            return false;
    });

    function validateName(){
        //if it's NOT valid
        if(name.val().length < 4){
            name.addClass("error");
            nameInfo.text("* Name Required");
            nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else{
            name.removeClass("error");
            nameInfo.text("*");
            nameInfo.removeClass("error");
            return true;
        }
    }
    function validateCaptcha(){

        $.post("captchaValidate.php?"+$("#contactForm").serialize(), {

            }, function(response){

            if(response==1)
            {
                captcha.removeClass("error");
                captchaInfo.text("*");
                captchaInfo.removeClass("error");
                return true;
            }
            else
            {
                captchaInfo.text("* Please enter the words you see in the box above. If you are having trouble seeing it, click the refresh button.");
                captchaInfo.addClass("error");
                captchaInfo.css({'float': 'left', 'margin-left': '5px'});
                return false;
            }

        });
    }
});

I again removed some of the code above to make this shorter but I left the validateName function so you can see how I pretty much did the rest of them.

In the validateCaptcha code it directs to this page/code:

<?php
session_start();

if(@strtolower($_REQUEST['captcha-code']) == strtolower($_SESSION['random_number']))
{

    echo 1;// YAY!

}
else
{
    echo 0; // invalid code
}
?>

Any help on this would be REALLY appreciated I've been stuck for so long! I have tried a few things already but nothing seems to work.

I have the captcha creating an image in captcha.php. On my contact php page, it calls for the image & it has a reload and everything works. I just can't seem to find a way to validate it.

Here is the code that creates the captcha image:

<?php
session_start();

$word_1 = '';
$word_2 = '';

for ($i = 0; $i < 4; $i++) 
{
    $word_1 .= chr(rand(97, 122));
}
for ($i = 0; $i < 4; $i++) 
{
    $word_2 .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $word_1.' '.$word_2;

$dir = '/addons/fonts/';

$image = imagecreatetruecolor(165, 50);

$font = "recaptchaFont.ttf"; // font style

$color = imagecolorallocate($image, 0, 0, 0);// color

$white = imagecolorallocate($image, 255, 255, 255); // background color white

imagefilledrectangle($image, 0,0, 709, 99, $white);

imagettftext ($image, 22, 0, 5, 30, $color, $dir.$font, $_SESSION['random_number']);

header("Content-type: image/png");

imagepng($image); 

?>

That is all that is in that file.

Next there is the code from my actual form (contact us page):

<form id="contactForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr>
    <td><span class="greyText">Enter text shown:</span></td>
    <td>
        <div id="captcha-wrap">
            <div class="captcha-box">
                <img src="captcha.php" alt="" id="captcha" />
            </div>
            <div class="text-box">
                <label>Type the two words:</label>
                <input name="captcha-code" type="text" id="captcha-code">
            </div>
            <div class="captcha-action">
                <img src="./images/captcha-refresh.png"  alt="" id="captcha-refresh" />
            </div>
        </div>
        <span id="captchaInfo">*</span>  
    </td>
</tr>
<tr>
    <td colspan="2">
            <div class="seperator">&nbsp;</div>

            <input type="submit" name="submit" class="styleButton" style="float:right;margin-right:10px" value="SUBMIT" /></td>
</tr>
</table>
</form>

I have other rows in that table for name, email etc, but I just removed it to make this shorter.

& in the document ready function for the contact page, I have this code to refresh the captcha when button is clicked:

 // refresh captcha
 $('img#captcha-refresh').click(function() {  

        change_captcha();
 });

 function change_captcha()
 {
    document.getElementById('captcha').src='jquery-captcha.php?rnd=' + Math.random();
 }

Next is the validation I have for the whole form itself. It works for everything but the captcha:

$(document).ready(function(){
    //global vars
    var form = $("#contactForm");
    var name = $("#name");
    var nameInfo = $("#nameInfo");
    var telephone = $("#telephone");
    var telephoneInfo = $("#telephoneInfo");
    var email = $("#email");
    var emailInfo = $("#emailInfo");
    var message = $("#message");
    var messageInfo = $("#messageInfo");
    var captcha = $("#captcha-code");
    var captchaInfo = $("#captchaInfo");

    //On blur
    name.blur(validateName);
    telephone.blur(validatePhone);
    email.blur(validateEmail);
    message.blur(validateMessage);
    captcha.blur(validateCaptcha);
    //On key press
    name.keyup(validateName);
    telephone.keyup(validatePhone);
    message.keyup(validateMessage);
    captcha.keyup(validateCaptcha);
    //On Submitting
    form.submit(function(){
        if(validateName() & validateEmail() & validatePhone() & validateMessage() & validateCaptcha())
            return true
        else
            return false;
    });

    function validateName(){
        //if it's NOT valid
        if(name.val().length < 4){
            name.addClass("error");
            nameInfo.text("* Name Required");
            nameInfo.addClass("error");
            return false;
        }
        //if it's valid
        else{
            name.removeClass("error");
            nameInfo.text("*");
            nameInfo.removeClass("error");
            return true;
        }
    }
    function validateCaptcha(){

        $.post("captchaValidate.php?"+$("#contactForm").serialize(), {

            }, function(response){

            if(response==1)
            {
                captcha.removeClass("error");
                captchaInfo.text("*");
                captchaInfo.removeClass("error");
                return true;
            }
            else
            {
                captchaInfo.text("* Please enter the words you see in the box above. If you are having trouble seeing it, click the refresh button.");
                captchaInfo.addClass("error");
                captchaInfo.css({'float': 'left', 'margin-left': '5px'});
                return false;
            }

        });
    }
});

I again removed some of the code above to make this shorter but I left the validateName function so you can see how I pretty much did the rest of them.

In the validateCaptcha code it directs to this page/code:

<?php
session_start();

if(@strtolower($_REQUEST['captcha-code']) == strtolower($_SESSION['random_number']))
{

    echo 1;// YAY!

}
else
{
    echo 0; // invalid code
}
?>

Any help on this would be REALLY appreciated I've been stuck for so long! I have tried a few things already but nothing seems to work.

Share Improve this question edited Dec 7, 2013 at 1:44 PhearOfRayne 5,0503 gold badges33 silver badges44 bronze badges asked Aug 9, 2012 at 17:07 CatiaCatia 2693 gold badges5 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Read this:--

PHP jQuery Validation CAPTCHA Code Sample

http://captcha.biz/doc/php/samples/php-jquery-validation-captcha-sample.html

PHP Captcha Code

http://www.9lessons.info/2011/01/php-captcha-code.html

jquery-validation / demo / captcha

https://github./jzaefferer/jquery-validation/blob/master/demo/captcha/index.php

If you don't mind using a simple math captcha, this one is very easy to integrate into your own code. It uses both PHP and jQuery, so it works with or without Javascript enabled. I wrote a tutorial on it and provide a project download with all the project files that works out of the box.

Making a Simple Math Captcha using both jQuery and PHP http://www.sinawiwebdesign./blog/topics/programming/jquery-and-php-and-catcha-tutorial/

I hope this helps.

Create simple capcha in php with jquery validation Example if you have any help for that

Create capcha code need three files

capcha.php
form.php
check-capcha.php

download font arial.ttf addded in fonts folder http://www5.miele.nl/apps/vg/nl/miele/mielea02.nsf/0e87ea0c369c2704c12568ac005c1831/07583f73269e053ac1257274003344e0?OpenDocument

<?php

session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {
    // this numbers refer to numbers of the ascii table (lower case)
    $string .= chr(rand(97, 122));
}

 $_SESSION['random_code'] = $string;

 $data['code'] = $string;
$dir = 'fonts/';

if(!is_dir($dir)){
mkdir($dir);
}

$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);

imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);

$save= "test.png";
  imagepng($image,$save);
  ob_start();
    imagedestroy($image);
echo json_encode($data);
?>

 form.php

 <script src="https://code.jquery./jquery-1.12.3.min.js"></script>
<script src="http://ajax.aspnetcdn./ajax/jquery.validate/1.15.0/jquery.validate.js"></script>
<script type="application/javascript">
$(document).ready(function(e) {

$('#test').validate({
rules:{
capcha:{required: true,
remote: {
                    url: "check-capcha.php",
                    type: "post",
data:{hiddencapcha:function(){return $('#hidden_capcha').val()}}
                 }
}
},
messages:{
capcha:{
remote:"invalid capcha"
}
}
});
$.ajax({
url: "capcha.php",
success: function( result ) {
var newd = JSON.parse(result);

$('input[name=hidden_capcha]').val(newd.code);


$('#capchas').attr('src',"test.png?"+ new Date().getTime());
},error: function(){ alert(result)}
});

$('#generate_capcha').click(function(){

$.ajax({
url: "capcha.php",
success: function( result ) {
var newd = JSON.parse(result);

$('input[name=hidden_capcha]').val(newd.code);

$('#capchas').attr('src',"test.png?"+ new Date().getTime());
},error: function(){ alert(result)}
});
});

});

</script>

<form name="test" id="test">

<span id="capchas_images"><img id="capchas" src="test.png" /></span> <a href="javascript:void(0)" id="generate_capcha">Refresh</a>
<input type="text" name="capcha" />
<input type="hidden" name="hidden_capcha" id="hidden_capcha" />
</form>

check-capch.php

<?php


if($_POST['capcha']==$_POST['hiddencapcha'])
{
echo "true";
}else{
echo "false";
    }
?>

http://myphpinformation.blogspot.in/2016/05/create-simple-capcha-in-php-with-jquery-validation.html

发布评论

评论列表(0)

  1. 暂无评论