.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> General >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Implementation of captcha in Registration form in php

Posted By:satyapriyanayak       Posted Date: March 31, 2014    Points: 200    Category: General    URL: http://www.dotnetspark.com  

In this article we will create a registration page with captcha implemented to it in php.
 

Introduction

In this article we will create a registration page with captcha implemented to it in php.

Before going forward we should know what is captcha?

CAPTCHA: - Completely Automated Public Turing test to tell Computers and Humans Apart. A captcha is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot. For example, humans can read distorted text but current computer programs can't.
Characteristics: A captcha is a means of automatically generating challenges which intends to:

.    Provide a problem easy enough for all humans to solve.
.    Prevent standard automated software from filling out a form, unless it is specially designed to circumvent specific CAPTCHA systems.


Here we use JavaScript for validation.

Table structure

-- phpMyAdmin SQL Dump
-- version 2.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 04, 2012 at 12:46 PM
-- Server version: 5.0.45
-- PHP Version: 5.2.5

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `Work`
--

-- --------------------------------------------------------

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `fullname` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `dob` varchar(255) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `company` varchar(255) NOT NULL,
  `designation` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state` varchar(255) NOT NULL,
  `zip` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `fax` varchar(255) NOT NULL,
  `website` varchar(255) NOT NULL,
  `country` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--


Now lets move to the coding part

For creating database connection

Config.php


<?php

 $sDbHost = 'localhost';
 $sDbName = 'Work';
 $sDbUser = 'root';
 $sDbPwd  = '';

$dbConn = mysql_connect ($sDbHost, $sDbUser, $sDbPwd) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($sDbName,$dbConn) or die('Cannot select database. ' . mysql_error());

?>

For creating random image

get_captcha.php


<?php
session_start();

$string = '';

for ($i = 0; $i < 5; $i++) {
    $string .= chr(rand(97, 122));
}

$_SESSION['random_number'] = $string;

$dir = 'fonts/';

$image = imagecreatetruecolor(165, 50);

// random number 1 or 2
$num = rand(1,2);
if($num==1)
{
    $font = "Capture it 2.ttf"; // font style
}
else
{
    $font = "Molot.otf";// font style
}

// random number 1 or 2
$num2 = rand(1,2);
if($num2==1)
{
    $color = imagecolorallocate($image, 113, 193, 217);// color
}
else
{
    $color = imagecolorallocate($image, 163, 197, 82);// color
}

$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image,0,0,399,99,$white);

imagettftext ($image, 20, 0, 10, 30, $color, $dir.$font, $_SESSION['random_number']);

header("Content-type: image/png");
imagepng($image);

?>

For Registration of users

registration.php


<?php
session_start();
include('config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Registration</title>

<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript"  src="js/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/simpleCal.js"></script>

<script language="javascript" type="text/javascript">

function validation()
{
    var formName=document.frm;
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

    var urlExp = /^(((ht|f){1}(tp:[/][/]){1})|((www.){1}))[-a-zA-Z0-9@:%_\+.~#?&//=]+$/;

    if(formName.fullname.value == "")
    {
        document.getElementById("fullname_label").innerHTML='Please Enter First Name';
        formName.fullname.focus();
        return false;
    }
    else
    {
        document.getElementById("fullname_label").innerHTML='';
    }

    if(formName.email.value == "")
    {
        document.getElementById("email_label").innerHTML='Please Enter Email';
        formName.email.focus();
        return false;
    }
    else
    {
        document.getElementById("email_label").innerHTML='';
    }

    if(!(formName.email.value).match(emailExp))
    {
        document.getElementById("email_label").innerHTML='Please Enter Valid Email';
        formName.email.focus()
        return false;
    }
    else
    {
        document.getElementById("email_label").innerHTML='';
    }

    if(formName.dob.value == "")
        {
            document.getElementById("dob_label").innerHTML='Please Enter Date of Birth';
            formName.dob.focus();
            return false;
        }
        else
        {
            document.getElementById("dob_label").innerHTML='';
        }

        if(formName.company.value == "")
        {
            document.getElementById("company_label").innerHTML='Please Enter Company';
            formName.company.focus();
            return false;
        }
        else
        {
            document.getElementById("company_label").innerHTML='';
        }


        if(formName.designation.value == "")
        {
            document.getElementById("designation_label").innerHTML='Please Enter Designation';
            formName.designation.focus();
            return false;
        }
        else
        {
            document.getElementById("designation_label").innerHTML='';
        }

        if(formName.address.value == "")
        {
            document.getElementById("address_label").innerHTML='Please Enter Address';
            formName.address.focus();
            return false;
        }
        else
        {
            document.getElementById("address_label").innerHTML='';
        }

        if(formName.city.value == "")
        {
            document.getElementById("city_label").innerHTML='Please Enter City';
            formName.city.focus();
            return false;
        }
        else
        {
            document.getElementById("city_label").innerHTML='';
        }



        if(formName.state.value == "")
        {
            document.getElementById("state_label").innerHTML='Please Enter State';
            formName.state.focus();
            return false;
        }
        else
        {
            document.getElementById("state_label").innerHTML='';
        }

        if(formName.zip.value == "")
        {
            document.getElementById("zip_label").innerHTML='Please Enter Zip Code';
            formName.zip.focus();
            return false;
        }
        else
        {
            document.getElementById("zip_label").innerHTML='';
        }

        if(formName.phone.value == "")
        {
            document.getElementById("phone_label").innerHTML='Please Enter Phone Number';
            formName.phone.focus();
            return false;
        }
        else
        {
            document.getElementById("phone_label").innerHTML='';
        }

        if(formName.fax.value == "")
        {
            document.getElementById("fax_label").innerHTML='Please Enter Fax Number';
            formName.fax.focus();
            return false;
        }
        else
        {
            document.getElementById("fax_label").innerHTML='';
        }

        if(formName.website.value == "")
            {
                document.getElementById("website_label").innerHTML='Please Enter Website';
                formName.website.focus();
                return false;
            }
            else
            {
                document.getElementById("website_label").innerHTML='';
            }


            if(!(formName.website.value).match(urlExp))
            {
                document.getElementById("website_label").innerHTML='Please Enter Valid Website';
                formName.website.focus()
                return false;
            }
            else
            {
                document.getElementById("website_label").innerHTML='';
    }

    if(formName.password.value == "")
    {
        document.getElementById("password_label").innerHTML='Please Enter Password';
        formName.password.focus();
        return false;
    }
    else
    {
        document.getElementById("password_label").innerHTML='';
    }


    if(formName.cpassword.value == "")
    {
        document.getElementById("cpassword_label").innerHTML='PleaseEnterConfirmPassword';
        formName.cpassword.focus();
        return false;
    }
    else
    {
        document.getElementById("cpassword_label").innerHTML='';
    }

    if(formName.password.value != formName.cpassword.value)
    {
        document.getElementById("cpassword_label").innerHTML='Passwords Missmatch';
        formName.cpassword.focus()
        return false;
    }
    else
    {
        document.getElementById("cpassword_label").innerHTML='';
    }

    if(formName.code.value == "")
            {
                document.getElementById("code_label").innerHTML='Please Enter Code';
                formName.code.focus();
                return false;
            }
            else
            {
                document.getElementById("code_label").innerHTML='';
        }





    if($('input:radio[name=gender]:checked').length==0){
            $('#gender_label').html('Please Choose option');
            return false;
        }
        if($('input:radio[name=gender]:checked').val()==1){
            if($('#gender').val()==''){
                $("#gender_label").html('Enter Your gender');
                return false;
            }else{
                $("#gender_label").html('');
            }
        }

    }

    $(function(){
        $('input:radio[name=gender]').click(function(){

        $('#gender_label').html('');
        });
        $('#gender').click(function(){
            $('#gender').val('');
        });
});


function Phone(evt)
{
     var charCode = (evt.which) ? evt.which : event.keyCode

     if ((charCode >= 97 && charCode <=122) || ((charCode >= 65 && charCode <=90)))
     {
        return false;
     }
     else if((charCode>=48 && charCode <=57) || charCode==43 || charCode==32 || charCode==45 || charCode==40 || charCode==41 || charCode==8)
     {
        return true;
     }
     else
     {
        return false;
     }
}

</script>
</head>
<script>

$(document).ready(function() {

     $('#Send').click(function() {

            $.post("post.php?"+$("#MYFORM").serialize(),
            {

            },

            function(response)
            {
        });

        return false;
     });

     // refresh captcha
     $('img#refresh').click(function() {

            change_captcha();
     });

     function change_captcha()
     {
         document.getElementById('captcha').src="get_captcha.php?rnd=" + Math.random();
     }

     function clear_form()
     {
         $("#name").val('');
        $("#email").val('');
        $("#message").val('');
     }
});



</script>

<?php
if($_REQUEST["action"]=='register')
{

    if(strtolower($_REQUEST['code']) == strtolower($_SESSION['random_number']))
    {
        $sql="select * from employee where     email ='$_REQUEST[email]'";
        $sql_row=mysql_query($sql);
        $num=mysql_num_rows($sql_row);
        if($num>0)
        {
            echo "<script>window.location.href='registration.php?msg=exist'</script>";
            exit;
        }
        else
        {

    $str="insert into employee set fullname='$_REQUEST[fullname]',email='$_REQUEST[email]',dob='$_REQUEST[dob]',gender='$_REQUEST[gender]',company='$_REQUEST[company]',designation='$_REQUEST[designation]',address='$_REQUEST[address]',city='$_REQUEST[city]',state='$_REQUEST[state]',zip='$_REQUEST[zip]',phone='$_REQUEST[phone]',fax='$_REQUEST[fax]',website='$_REQUEST[website]',country='$_REQUEST[country]',password='$_REQUEST[password]'";
    mysql_query($str);
    $mesg="Success";
    echo "<script>window.location.href='welcome.php'</script>";
    //exit;
        }
    }
    else
    {
        echo "<script>window.location.href='registration.php?msg=invalid&fullname=$_REQUEST[fullname]&email=$_REQUEST[email]&dob=$_REQUEST[dob]&company=$_REQUEST[company]&designation=$_REQUEST[designation]&address=$_REQUEST[address]&city=$_REQUEST[city]&state=$_REQUEST[state]&zip=$_REQUEST[zip]&phone=$_REQUEST[phone]&fax=$_REQUEST[fax]&website=$_REQUEST[website]'</script>";
        exit;

    }
}

?>

<body>

<form method="post" id="frm" name="frm" action="registration.php?action=register" onSubmit="return validation();">
<table width="500" border="0">

<?php if($_REQUEST["msg"]=='invalid') {   ?>
    <tr>
      <td height="30">&nbsp;</td>
      <td class="redText2">Invalid captcha code </td>
    </tr>
  <?php } ?>

 <?php if($_REQUEST[msg]=='exist') { ?>
  <tr>
    <td height="30">&nbsp;</td>
    <td class="redText2">Email Address is already in use.Try with another. </td>
  </tr>
  <?php } ?>
   <?php if($_REQUEST[msg]=='success') { ?>
  <tr>
    <td height="30">&nbsp;</td>
    <td class="greenText">Registered Successfully </td>
  </tr>
  <?php } ?>
<tr>
 <td class="deepbluetextbold"><b>Employee Registration</b></td>
 </tr>
  <tr>
    <td class="colouredCell">Name*</td>
    <td>
      <input type="text"  name="fullname" id="fullname" autocomplete="off" value="<?php echo $_REQUEST[fullname]; ?>"/>&nbsp; <label id="fullname_label" class="level_msg"></label>    </td>
  </tr>
  <tr>
    <td class="colouredCell">Email*</td>
    <td><input type="text" name="email"  id="email" autocomplete="off" value="<?php echo $_REQUEST[email]; ?>"/>&nbsp; <label id="email_label" class="level_msg"></label></td>
  </tr>
<tr>
      <td class="colouredCell">Date of Birth*</td>
      <td><input type="text" name="dob" id="dob" autocomplete="off" value="<?php echo $_REQUEST[dob]; ?>"/>&nbsp; <label id="dob_label" class="level_msg"></label>

      <a href="#" onclick="scwShow (document.getElementById('dob'), event); return false;" />
      <img border="0"  alt="" src="images/calendar.png" />
      <span id="lbldob" style="color:Red;font-weight:bold;"></span>
      </td>
  </tr>
  <tr>
      <td class="colouredCell">Gender*</td>
      <td>
        <input name="gender" type="radio" value="male"/>Male
        <input name="gender" type="radio" value="female"/>Female
        &nbsp; <label id="gender_label" class="level_msg"></label>    </td>
  </tr>
  <tr>
      <td class="colouredCell">Company*</td>
      <td><input type="text" name="company" id="company" autocomplete="off" value="<?php echo $_REQUEST[company]; ?>"/>&nbsp; <label id="company_label" class="level_msg"></label></td>
  </tr>
  <tr>
      <td class="colouredCell">Designation*</td>
      <td><input type="text" name="designation" id="designation" autocomplete="off" value="<?php echo $_REQUEST[designation]; ?>"/>&nbsp; <label id="designation_label" class="level_msg"></label></td>
  </tr>
  <tr>
      <td class="colouredCell">Street Address*</td>
      <td><input type="text" name="address" id="address" autocomplete="off" value="<?php echo $_REQUEST[address]; ?>"/>&nbsp; <label id="address_label" class="level_msg"></label></td>
  </tr>
  <tr>
      <td class="colouredCell">City*</td>
      <td><input type="text" name="city" id="city" autocomplete="off" value="<?php echo $_REQUEST[city]; ?>"/>&nbsp; <label id="city_label" class="level_msg"></label></td>
  </tr>
  <tr>
        <td class="colouredCell">State*</td>
        <td><input type="text" name="state" id="state" autocomplete="off" value="<?php echo $_REQUEST[state]; ?>"/>&nbsp; <label id="state_label" class="level_msg"></label></td>
  </tr>
  <tr>
        <td class="colouredCell">Zip Code*</td>
        <td><input type="text" name="zip" id="zip" autocomplete="off" value="<?php echo $_REQUEST[zip]; ?>"/>&nbsp; <label id="zip_label" class="level_msg"></label></td>
  </tr>
  <tr>
        <td class="colouredCell">Phone*</td>
        <td><input type="text" name="phone" id="phone" autocomplete="off" onKeyPress="return Phone(event);" value="<?php echo $_REQUEST[phone]; ?>"/>&nbsp; <label id="phone_label" class="level_msg"></label></td>
  </tr>
  <tr>
        <td class="colouredCell">Fax*</td>
        <td><input type="text" name="fax" id="fax" autocomplete="off" onKeyPress="return Phone(event);" value="<?php echo $_REQUEST[fax]; ?>"/>&nbsp; <label id="fax_label" class="level_msg"></label></td>
  </tr>
  <tr>
          <td class="colouredCell">Website*</td>
          <td><input type="text" name="website" id="website" autocomplete="off" value="<?php echo $_REQUEST[website]; ?>"/>&nbsp; <label id="website_label" class="level_msg"></label></td>
  </tr>


  <tr>
          <td class="colouredCell">Country*</td>
          <td>
          <select class="" id="country" name="country" aria-required="true">
                              <option value=""    selected="selected">Select One</option>
                              <option value="af"   >Afghanistan</option>

                              <option value="ax"   >Aland Islands</option>
                              <option value="al"   >Albania</option>
                              <option value="dz"   >Algeria</option>
                              <option value="as"   >American Samoa</option>
                              <option value="ad"   >Andorra</option>
                              <option value="ao"   >Angola</option>

                              <option value="ai"   >Anguilla</option>
                              <option value="aq"   >Antarctica</option>
                              <option value="ag"   >Antigua and Barbuda</option>
                              <option value="ar"   >Argentina</option>
                              <option value="am"   >Armenia</option>
                              <option value="aw"   >Aruba</option>

                              <option value="au"   >Australia</option>
                              <option value="at"   >Austria</option>
                              <option value="az"   >Azerbaijan</option>
                              <option value="bs"   >Bahamas</option>
                              <option value="bh"   >Bahrain</option>
                              <option value="bd"   >Bangladesh</option>

                              <option value="bb"   >Barbados</option>
                              <option value="by"   >Belarus</option>
                              <option value="be"   >Belgium</option>
                              <option value="bz"   >Belize</option>
                              <option value="bj"   >Benin</option>
                              <option value="bm"   >Bermuda</option>

                              <option value="bt"   >Bhutan</option>
                              <option value="bo"   >Bolivia</option>
                              <option value="ba"   >Bosnia and Herzegovina</option>
                              <option value="bw"   >Botswana</option>
                              <option value="bv"   >Bouvet Island</option>
                              <option value="br"   >Brazil</option>

                              <option value="io"   >British Indian Ocean Territory</option>
                              <option value="vg"   >British Virgin Islands</option>
                              <option value="bn"   >Brunei</option>
                              <option value="bg"   >Bulgaria</option>
                              <option value="bf"   >Burkina Faso</option>
                              <option value="bi"   >Burundi</option>

                              <option value="kh"   >Cambodia</option>
                              <option value="cm"   >Cameroon</option>
                              <option value="ca"   >Canada</option>
                              <option value="cv"   >Cape Verde</option>
                              <option value="ky"   >Cayman Islands</option>
                              <option value="cf"   >Central African Republic</option>

                              <option value="td"   >Chad</option>
                              <option value="cl"   >Chile</option>
                              <option value="cn"   >China</option>
                              <option value="cx"   >Christmas Island</option>
                              <option value="cc"   >Cocos (Keeling) Islands</option>
                              <option value="co"   >Colombia</option>

                              <option value="km"   >Union of the Comoros</option>
                              <option value="cg"   >Congo</option>
            &

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend