In this tutorial I want explain how to create a Captcha in PHP. We are using some of the features available in PHP for creating an image. This is very simple and basic tutorial and we are not using any custom fonts for generating captcha image. And we know that captcha code used to avoid spam/abuse or auto-submission.
Download Script Live Demo
About Author
Captcha.php
<?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);
?>
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);
?>
Verifying captcha code is equal or not
Here we are storing a captcha code in SESSION variable and while verifying we have to compare the session variable with user entered data.
$_SESSION['cap_code'] - is having actual captcha code
$_POST['captcha'] - user entered captcha code
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($_POST['captcha'] == $_SESSION['cap_code'])
{
// Captcha verification is Correct. Do something here!
}
else
{
// Captcha verification is wrong. Take other action
}
}
?>
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($_POST['captcha'] == $_SESSION['cap_code'])
{
// Captcha verification is Correct. Do something here!
}
else
{
// Captcha verification is wrong. Take other action
}
}
?>
Read This
The below html/CSS/Jquery code I used is just for an extra enhancement only and all the code is not needed actually. The above code is enough to check whether Human Verification is correct or wrong.
index.php
Contains HTML and PHP code. Image scr='captcha.php'
<?php
session_start();
$cap = 'notEq'; // This php variable is passed to jquery variable to show alert
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 = '';
}
}
?>
<html>
<body>
<form action="" method="post">
<label>Name:</label><br/>
<input type="text" name="name" id="name"/>
<label>Message:</label><br/>
<textarea name="msg" id="msg"></textarea>
<label>Enter the contents of image</label>
<input type="text" name="captcha" id="captcha" />
<img src='captcha.php' />
<input type="submit" value="Submit" id="submit"/>
</form>
<div class="cap_status"></div>
</body>
</html>
session_start();
$cap = 'notEq'; // This php variable is passed to jquery variable to show alert
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 = '';
}
}
?>
<html>
<body>
<form action="" method="post">
<label>Name:</label><br/>
<input type="text" name="name" id="name"/>
<label>Message:</label><br/>
<textarea name="msg" id="msg"></textarea>
<label>Enter the contents of image</label>
<input type="text" name="captcha" id="captcha" />
<img src='captcha.php' />
<input type="submit" value="Submit" id="submit"/>
</form>
<div class="cap_status"></div>
</body>
</html>
Javascript
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<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');
}
}
});
</script>
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<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');
}
}
});
</script>
CSS
body{
width: 600px;
margin: 0 auto;
padding: 0;
}
#form{
margin-top: 100px;
width: 350px;
outline: 5px solid #d0ebfe;
border: 1px solid #bae0fb;
padding: 10px;
}
#form label
{
font:bold 11px arial;
color: #565656;
padding-left: 1px;
}
#form label.mandat
{
color: #f00;
}
#form input[type="text"]
{
height: 30px;
margin-bottom: 8px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}
#form textarea
{
width: 340px;
height: 80px;
resize: none;
margin: 0 0 8px 1px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}
#form img
{
margin-bottom: 8px;
}
#form input[type="submit"]
{
background-color: #0064aa;
border: none;
color: #fff;
padding: 5px 8px;
cursor: pointer;
font:bold 12px arial;
}
.error
{
border: 1px solid red;
}
.cap_status
{
width: 350px;
padding: 10px;
font: 14px arial;
color: #fff;
background-color: #10853f;
display: none;
}
.cap_status_error
{
background-color: #bd0808;
}
width: 600px;
margin: 0 auto;
padding: 0;
}
#form{
margin-top: 100px;
width: 350px;
outline: 5px solid #d0ebfe;
border: 1px solid #bae0fb;
padding: 10px;
}
#form label
{
font:bold 11px arial;
color: #565656;
padding-left: 1px;
}
#form label.mandat
{
color: #f00;
}
#form input[type="text"]
{
height: 30px;
margin-bottom: 8px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}
#form textarea
{
width: 340px;
height: 80px;
resize: none;
margin: 0 0 8px 1px;
padding: 5px;
font: 12px arial;
color: #0060a3;
}
#form img
{
margin-bottom: 8px;
}
#form input[type="submit"]
{
background-color: #0064aa;
border: none;
color: #fff;
padding: 5px 8px;
cursor: pointer;
font:bold 12px arial;
}
.error
{
border: 1px solid red;
}
.cap_status
{
width: 350px;
padding: 10px;
font: 14px arial;
color: #fff;
background-color: #10853f;
display: none;
}
.cap_status_error
{
background-color: #bd0808;
}
I think that some spambots wouldnt have any problem to read this text from image.
ReplyDeletethis is awesome...i'm looking out for this help to be included ...great help
ReplyDelete@Anonymous hmm maybe but am not sure it would get it every time, like 1/10 something :P not sure, but it looks great to me very nice script, thanks :)
ReplyDeleteIts a good tutorial and validation is awesome. Though spambots could read this text from image, i believe it still reduces 95% chances of hacking.
ReplyDelete@dskanth : You are correct !
ReplyDeleteJust use recaptcha from Google?
ReplyDeleteGood tutorial, I love the Joker image jaja :D
ReplyDeleteThanks for posting this. You've got a lot of good code examples on your site. I can't wait to try them out. Keep up the excellent work.
ReplyDeletewow great code. think i might use this on my site
ReplyDeleteThanks for the code :-)
ReplyDeleteThat was really great tutorial and thanks for the download script. I think it will be helpful to everyone who like to put security from spam bot in their forms.
ReplyDeleteThe scripts look nice, however, could you please explain what to do with them and where to insert into html pages and where to place php files in order to make them work (for us complete novices)?
ReplyDeleteThanks,
Not trying to discourage the effort, but this script can be cracked 95% of the time.. yes 95% of the time. even google's reCaptcha was cracked in jan 2011. not longer safe.
ReplyDeleteI downloaded the script. I haven't use it yet, but the live demo looks pretty cool.
ReplyDeleteThank you for your work.
I can't get $_SESSION['cap_code']. $_SESSION['cap_code'] value is "".
ReplyDeleteã… .ã…
It has a bug, because if you do not fill the captcha and delete the session, you true results
ReplyDeleteIt's really good article
ReplyDeletedemo not getting :(
ReplyDeleteThanks for this post.Realy it was very useful for me.
ReplyDeleteGood work..........
ReplyDeleteHi - love this stuff but I am so new to this I cannot fathom where to put it and what to modify. Can you suggest something with my file
ReplyDeleteRight now I have no error check on "security_code" or "Captcha" as you called it.
I have messages if they don't fill in email and such (not pretty ones just text showing up in div might nice to have a pop up)
I also have a confirmation that I cannot place properly - it shows up in my main body. This would be nice as a modal box too.
Can you help me? Take a look at my Contact page on robertechcs.com and see what I mean.
I can load my files to an ftp if you can help
Thanks a mil
nice
ReplyDeleteExcellent code thank you...
ReplyDeletethank for posting ....
ReplyDeleteLatest method for avoid spam filter by using motion(Just Draw shape).
ReplyDeleteVery interesting plugin for Motion captch here,after long search i found that..
http://techpdf.in/blog/2012/02/motion-captcha-using-jquery/
have a nice day...:)
thanks man goood job
ReplyDeleteThanks friend..
ReplyDeletewhere do i put the email to be sent?
ReplyDeleteExcellent, I'm going to put this up on my site soon.
ReplyDeleteSir i am very happy for this code.. because before i am using a big file for captcha code...but you r excellent..i love it sir..thanks for this...
ReplyDeletei guess to check captcha in javascript jquery we should use ajax to get session captcha... otherwise any one can inspect element it..
ReplyDeletebut what if i had many tabs open with the same page? $_SESSION[var] will not work properly and only one page will work
ReplyDeletevery good post and very useful site
ReplyDeleteHow about if we change the color and font size also position? Hope you will respon my question.
ReplyDeletethanks its working
ReplyDeletethanks for this code....
ReplyDeleteThanks for this code..
ReplyDeleteThanks !! Nice Scripting !!
ReplyDeleteThanks for your CAPTCHA, it is nice and simple. User's note: in normal circumstances, session_start() is not called until the CAPTCHA image is rendered. This is fine if your processing code is immediately after the form, but if it's before (or your processing happens on a separate page), then you'll need to call session_start() manually.
ReplyDeleteNice and simple (y)
ReplyDeleteYou did not mentioned the bg image is need in your post plz note to add that one. good code
ReplyDeleteI have problem with line 'header("Content-type: image/jpeg");' in page chaptcha.php when it's run to this line , it's show message "can not displayed because contain errors" any help ?it's happend when i marge ur code with my code.
ReplyDeleteNice Code Buddy I will definitely follow you
ReplyDeleteThanks
hey buddy..please specify the parameter of taxcolor
ReplyDeletehow change font size
ReplyDeletegreat source thanks.
ReplyDeleteThis was a great piece of code as my client is STILL using html files.
ReplyDeleteI have an issue with the background image not displaying so there is no way to submit the form now??
This code has been great – I am now thought having an issue with the captcha image displaying.
ReplyDeleteClient is still using HTML files for their website and now quick solution? Would appreciate the help.
My code has an error, for gd library? what should i do?
ReplyDelete