Showing posts with label Create simple capcha in php with jquery validation. Show all posts
Showing posts with label Create simple capcha in php with jquery validation. Show all posts

Thursday 5 May 2016

Create simple capcha in php with jquery validation

Create simple capcha in php with jquery validation

Create capcha code need three files

capcha.php
form.php
check-capcha.php

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.com/jquery-1.12.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/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";
    }
?>