This blog post demonstrate you, how to implement your own simple captcha using PHP, jQuery and AJAX in form.
Description : Captcha is basically a random generate captcha string and which can be stored in session variable for further use.
After that, the generated string is bunched with an image to pretend as a single image in such a way that only human being is able read it.
- Here we used an alphanumeric string and stored it in a PHP variable.
- This variable is then passed in str_shuffle() function.
- After shuffling, we took sub-string of defined length and stored it in a session (global variable).
- Then, we convert the string into image and used it in our form.
HTML File: index.html
We have created a simple HTML form.
<!DOCTYPE html>
<html>
<head>
<title>Create Captcha using PHP,jQuery and AJAX</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<!-- Required Div Starts Here -->
<h2>Create Captcha using PHP,jQuery and AJAX</h2>
<form id="myForm" method="post" name="myForm">
<h3>Fill Your Information!</h3>
<table>
<tr>
<td>Username:</td>
<td>
<input id='username1' name='username' type='text'>
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input id='email1' name='email' type='text'>
</td>
</tr>
<tr>
<td>
</td>
<td id="imgparent">
<div id="imgdiv">
<img id="img" src="captcha.php">
</div>
<img id="reload" src="reload.png">
</td>
</tr>
<tr>
<td>Enter Image Text:</td>
<td>
<input id="captcha1" name="captcha" type="text">
</td>
</tr>
<tr>
<td><input id="button" type='button' value='Submit'></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
CAPTCHA Generating code: captcha.php
Here, we generate our CAPTCHA code in PHP as mentioned above.
<?php
session_start(); // Staring Session
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; // Initializing PHP variable with string
$captchanumber = substr(str_shuffle($captchanumber), 0, 6); // Getting first 6 word after shuffle.
$_SESSION["code"] = $captchanumber; // Initializing session variable with above generated sub-string
$image = imagecreatefromjpeg("bj.jpg"); // Generating CAPTCHA
$foreground = imagecolorallocate($image, 175, 199, 200); // Font Color
imagestring($image, 5, 45, 8, $captchanumber, $foreground);
header('Content-type: image/png');
imagepng($image);
?>
jQuery and Ajax Code : script.js
here, we performed validation of other fields and sending user input CAPTCHA text via Ajax to verfy.php file.
$(document).ready(function() {
//change CAPTCHA on each click or on refreshing page
$("#reload").click(function() {
$("img#img").remove();
var id = Math.random();
$('<img id="img" src="captcha.php?id='+id+'"/>').appendTo("#imgdiv");
id ='';
});
//validation function
$('#button').click(function() {
var name = $("#username1").val();
var email = $("#email1").val();
var captcha = $("#captcha1").val();
if (name == '' || email == '' || captcha == '')
{
alert("Fill All Fields");
}
else
{ //validating CAPTCHA with user input text
var dataString = 'captcha=' + captcha;
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
success: function(html) {
alert(html);
}
});
}
});
});
VERIFYING CAPTCHA : verify.php
verifying user input CAPTCHA text with generated CAPTCHA string, stored in session variable.
<?php
//CAPTCHA Matching code
session_start();
if ($_SESSION["code"] == $_POST["captcha"]) {
echo "Form Submitted successfully....!";
} else {
die("Wrong TEXT Entered");
}
?>
CSS File: style.css
Styling HTML elements.
@import "http://fonts.googleapis.com/css?family=Fauna+One|Muli";
#mainform{
width:960px;
margin:20px auto;
padding-top:20px;
font-family:'Fauna One',serif
}
#mainform h2{
width:100%;
float:left;
text-align:center;
margin-top:35px
}
.innerdiv{
width:65%;
float:left
}
form{
background-color:#fff;
color:#123456;
box-shadow:0 1px 1px 1px gray;
width:500px;
margin:50px 250px 0 50px;
float:left;
height:430px
}
h3{
margin-top:0;
margin-bottom:10px;
color:#fff;
background-color:#3C599B;
text-align:center;
width:100%;
height:50px;
padding-top:30px
}
input{
width:250px;
height:30px;
border-radius:3px;
padding:2px;
box-shadow:0 0 10px #a9a9a9;
margin:10px
}
input[type=button]{
background-color:#3C599B;
border:1px solid #fff;
font-family:'Fauna One',serif;
font-weight:700;
font-size:18px;
color:#fff;
margin-top:15px
}
span{
color:green
}
#myForm div{
color:red;
font-size:14px
}
table{
margin-left:40px
}
#imgdiv{
width:160px;
float:left;
margin-left:20px
}
#reload{
float:right;
margin-right:40px
}
Conclusion:
So, in this way you can create your own php captcha, keep following to learn more.
22 Replies to “Captcha Code in PHP and jQuery”
code does not work!
Hello Af,
Let me know what error you are getting so that I check it at my end.
Your captcha does not work in firefox
Hello Gaurav,
Thanks for looking into it.
We sincerely apologize for this inconvenience. Now, we have updated our codes and it’s reference.
Now captcha image refresh working on any browsers.
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
Thanks man, works great!
Thanks for your appreciation !
Keep reading our blog posts.
This is good captcha code but reload image is not working in internet explorer and firefox.
I too checked in firefox. Reload image is not working.
Thank you very much for the captcha code. But as Mr.Sanjay said, the reload image wasn’t working in the internet explorer and firefox.
But I found the issue, there is a image cache clearing issue with firefox. You just need to modify the script.js as follows:
//change CAPTCHA on each click or on refreshing page
$(“#reload”).click(function() {
$(“#img”).remove();
var d=new Date();
//$(”).empty().appendTo(“#imgdiv”);
$(‘#imgdiv’).empty().append(”);
});
you can see in the above code I have added a variable “d” for date function and appended in the capctha.php
Let me know any queries.
Thanks Robin for the code.
Hello Sanjay,
You need to do some changes for firefox in script.js file.
Use this : $(“#reload”).click(function() {
$(“#img”).remove();
location.reload();
});
Hope that will work for you.
Regards,
FormGet Team.
Thank you very much for the captcha code
I used this code to solve the bug of reload button it worked fine for me
$(“#reload”).click(function() {
$(“#img”).remove();
$(‘#imgdiv’).append(”)
$(‘#img’).attr(‘src’, ‘../php/captcha.php?’+new Date().getTime());
});
maybe it is useful for someone?
Totally works! Thanks a lot
refresh image dosen’t work ???
Hello Vaibhav,
Now, we have updated our codes and it’s reference.
Now captcha image refresh button working on any browsers which you use like( IE, Firefox, chrome etc ).
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
The captcha image is not working.
even it is not getting load..
please get me back soon..
Hello Kapil,
Thanks for looking into it.
We sincerely apologize for this inconvenience. Now, we have updated our codes and it’s reference.
Now captcha image refresh working on any browsers.
Keep reading our other blog posts.. for getting more coding tricks.
Thanks & Regards,
FormGet.com
Your blog posts are really useful ??
Thanks a lot ✋?
Does not work not show images with captcha ………………..
I am using your site code in my registration page then captcha is not properly work without check the value of textbox with captcha image form is submitted successfully(when captcha text have wrong value).in my registration page i am using javascript validation.Only for captcha we use jquery validator
Hello Sir / Mam..
I workout this coding.i got one error in this coding..when i run this image will not be display on screen.suppose i want to create any database for this error?
Hi, Great article, but there is a problem with the Captcha generating code…after I replaced it, then it begun to work and show…But thank you very much
Your validation doesn’t work @ email sections.