Login Form with CAPTCHA validation in PHP - MySQL


CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart. CAPTCHA helps to blocks automated systems and prevents spam in website comment sections.

First we have to Enable GD2 Library

  1. Open you php.ini file
  2. Search for following line and remove the semicolon(;).
         ;extension=php_gd2.dll
    change to
         extension=php_gd2.dll

The following example shows, how to validate CAPTCHA in Login Form with PHP - MySQL

Login Form with CAPTCHA validation in PHP
Table structure for `users` table
CREATE TABLE IF NOT EXISTS `users` (
  `UID` int(11) NOT NULL AUTO_INCREMENT,
  `UNAME` varchar(150) NOT NULL,
  `UPASS` varchar(150) NOT NULL,
  PRIMARY KEY (`UID`)
);
captcha.php
<?php 
  session_start();
  
  function randText(){
    $txt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $str="";
    for($i=0;$i<5;$i++)
    {
      $index=rand(0,strlen($txt)-1);
      $str.=$txt[$index];
    }
    return $str;
  }

  header("Content-type:image/png");
  $image=imagecreate(70,30);
  $backColor=imagecolorallocate($image,168,167,165);
  $txtColor=imagecolorallocate($image,250,250,250);
  $code=randText();
  $_SESSION["captcha"]=$code;
  imagestring($image,5,15,7,$code,$txtColor);
  imagepng($image);
  imagecolordeallocate($backColor);
  imagecolordeallocate($txtColor);
  imagedestroy($image);
?>
login.php
<?php session_start();?>
<html>
  <head>
    <title>Login Form with CAPTCHA in PHP</title>
    <style>
      .frm{
        width:300px;
        margin:70px auto;
      }
      .frm input{
        width:100%;
        padding:5px 2px;
      }        
    </style>
  </head>
  <body>
    <h1 align='center'>Login Form with CAPTCHA in PHP</h1>

    <?php 
    
      $data=[
        "uname"=>"",
        "upass"=>"",
        "err_uname"=>"",
        "err_upass"=>"",
        "err_msg"=>"",
      ];
      if($_SERVER["REQUEST_METHOD"]=="POST"){
        
        $data["uname"]=$_POST["uname"];
        $data["upass"]=$_POST["upass"];
        
        if($_SESSION["captcha"]==$_POST["code"]){
          
          #Database Connection
          $con=mysqli_connect("localhost","root","","db_sample");
          
          $uname=mysqli_real_escape_string($con,$_POST["uname"]);
          $upass=mysqli_real_escape_string($con,$_POST["upass"]);
          
          $sql="select * from users where UNAME='{$uname}'";
          $res=$con->query($sql);
          
          if($res->num_rows>0){
            
            $row=$res->fetch_assoc();
            if($row["UPASS"]===$upass){
              
              $_SESSION["login_details"]=$row;
              header("location:home.php");
              
            }else{
              #Set error message for Invalid Password 
              $data["err_upass"]="Invalid Password";
            }
          }else{
            #Set error message for Invalid User Name 
            $data["err_uname"]="Invalid User Name";
          }
        }else{
          #Set error message for Incorrect CAPTCHA 
          $data["err_msg"]="Please Enter Correct CAPTCHA";
        }
      }
    ?>

    <form method='post' action='<?php echo $_SERVER["REQUEST_URI"]; ?>' class='frm' autocomplete='off'>
	
      <p><input type='text' name='uname' required placeholder='Enter User Name' value='<?php echo $data["uname"]; ?>'></p>
      <p style='color:red;'><?php echo $data["err_uname"]; ?></p>
      
      <p><input type='password' name='upass' required placeholder='Enter Password' value='<?php echo $data["upass"]; ?>'></p>
      <p style='color:red;'><?php echo $data["err_upass"]; ?></p>
      
      <p><input type='text' name='code' required placeholder='Enter Captcha'></p>
      <p style='color:red;'><?php echo $data["err_msg"]; ?></p>
      
      <img src="captcha.php">
      
      <p><input type='submit' name='submit' value='Login'></p>
    </form>
  </body>
</html>
home.php
<?php 
  session_start();
  if(!isset($_SESSION["login_details"])){
    header("location:login.php");
  }
?>
<html>
  <head>
    <title>Home</title>
  </head>
  <body>
    <h2>Welcome : <?php echo $_SESSION["login_details"]["UNAME"]; ?></h2>
  </body>
</html>

Download Source Code Click Here.