PHP contact form with captcha verification code. Why we use to Captcha in website, it will protects your website for spammers and robots. Here i have used ajax script to check validate captcha code. For creating images and text you have download libraries file.
Php captcha libraries file
$captcha->CreateImage(); - create random image.
$captcha = new SimpleCaptcha(); - create new captcha random number.
Note captcha.php file libraries file.
Index.php
<html> <head> <title>Captcha test | mostlikers</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="cap_ajax.js"></script> </head> <body> <form id="form_captcha" method="post"> <img src="captcha.php" id="captcha" /> <a href="#" id="captcha_text"><img id="refresh-captcha" src="refresh_1.png"></a> <br/> <input required type="text" name="captch" id="captch" /> <div class="error captcha_error"></div> <br/> <input name="submit" value="submit" class="cap_submit" type="button" /> </form> </body> </html>
cap_ajax.js
$(document).ready(function(){ $(document).on("click", '#captcha_text', function(event) { document.getElementById('captcha').src='captcha.php?'+Math.random(); document.getElementById('captcha-form').focus(); return false; }); $(document).on("click", '.cap_submit', function(event) { var captch = $('#captch').val(); var dataString = 'captch=' + captch; $.ajax({ type: "POST", url: "captcha_verify.php", data: dataString, dataType : "html", success: function(data){ if(data=='0') { $('.captcha_error').html('your entered code is incorrect.'); } else if(data=='1') { alert('your entered code is correct.'); location.reload(); } else{ alert('Please Enter verfication text'); } } }); return false; }); });
captcha_verify.php
<?php session_start(); if (!empty($_POST['captch'])) { if (empty($_SESSION['captcha']) || trim(strtolower($_POST['captch']))
!= $_SESSION['captcha'] || empty($_POST['captch'])) { echo '0'; } else { echo '1'; unset($_SESSION['captcha']); } } ?>
I hope this post helpful for you, Share your comments below.
No comments:
Post a Comment