Simple Captcha code in Php and Javascript
Last Updated on
In websites ,captcha is used to find if you are human being or machine.
In most cases captcha using in forms like (contact form,Registration form etc…).In this tutorial I have create a very simple captcha code in PHP and javascript.
First I create a new file called contact.php .this file contains html contact form with captcha field.
<?php //Random Number Generation $rand=substr(rand(),0,4);//only show 4 numbers ?> <form method="post" action="<?php $_SERVER['PHP_SELF']?>" name="form1"> <table> <tr> <td>Name:</td> <td><input type="text" name="name"> <span id="name" class="color"></span> </td> </tr> <tr> <td>Enter Captcha</td> <td><input type="text" name="chk" id="chk"> <span id="error" class="color"></span> </td> </tr> <tr> <td> </td> <td><input type="text" value="<?=$rand?>" id="ran" readonly="readonly" class="captcha"> <input type="button" value="Referesh" onclick="captch()" /></td> </tr> <tr> <td colspan="2"> <input type="submit" name="check" onclick="return validation();"> </td> </table> </form>
In this above code I create a simple contact form with basic fields and user entered captcha field.I show a random number using php rand function. This function used to show a random string.
Next I need to compare user entered captcha and shown captcha both are same. if not same display error message.using javascript .below code explain it
<script type="text/javascript"> //Javascript Captcha validation function validation() { if(document.form1.name.value=="") { document.getElementById("name").innerHTML="Enter your Name!"; document.form1.name.focus(); return false; } if(document.form1.chk.value=="") { document.getElementById("error").innerHTML="Enter Captcha!"; document.form1.chk.focus(); return false; } if(document.form1.ran.value!=document.form1.chk.value) { document.getElementById("error").innerHTML="Captcha Not Matched!"; document.form1.chk.focus(); return false; } return true; } </script>
Next add refresh button in this part I need to use javascript for regenerate random number and put on captcha field in client side.below code done this work
<script type="text/javascript"> //Javascript Referesh Random String function captch() { var x = document.getElementById("ran") x.value = Math.floor((Math.random() * 10000) + 1); } </script>
Finally form contains no errors submit the form
<?php if(isset($_POST['check'])) { echo "Form Submitted<br>"; echo "Name:".' '.$name=$_POST['name']; } ?>
using this captcha preventing default form action without any error… redirecting to same page. why??