In this article, I will explain how to create Login with Math CAPTCHA in PHP using jQuery. A CAPTCHA is a kind of challenge-response system designed to differentiate humans from robotic software programs. CAPTCHAs are used as security checks to deter spammers and hackers. we use captcha to secure our website. if you are a senior web developer you must have created plenty of Login and Register system with CAPTCHA challenge already. They maybe exist in a content management system and E-commerce projects. if you just started web development, you are certainly going to experience lots of Login and Register creation work in your later career.

1-Creating Database

  • Open PHPMyAdmin in your Browser
  • Click on Database Tab Display on Topside
  • Give the Database name “captcha”.
  • After Creating Database Open it.
  • Click on SQL Tab on Top area
  • Copy the Below Source Code and paste it.
  • Then Click on Go.
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jul 28, 2018 at 11:05 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `captcha`
--

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

--
-- Table structure for table `user`
--

CREATE TABLE IF NOT EXISTS `user` (
`user_id` int(11) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(12) NOT NULL,
  `name` varchar(50) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`user_id`, `username`, `password`, `name`) VALUES
(1, 'admin', 'admin', 'Administrator'),
(2, 'deepak', '00124578', 'Deepak Kumar');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
 ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

OR Import DB File

After Downloading the source code extract it in your root folder.

  • Open PHPMyAdmin in your Browser
  • Click on Database Tab Display on Topside
  • Give the Database name “captcha”.
  • After Creating Database Open it.
  • Click on Import Tab on Top area
  • You can Find Db file in  Downloaded source code Select it.
  • Then Click on Go.

2- Creating Database Connection

After import Database File then next step is creating a database connection using PHP copy the below code and save it is as “conn.php”.

<?php
	$conn = new mysqli('localhost', 'root', '', 'captcha');
	
	if(!$conn){
		die("Error: Failed to connect to database!");
	}
?>

3 – Creating Login and Register Form using HTML & BOOTSTRAP

in this step, we are going to creating the login and register form using HTML and Bootstrap where register form open in modal and login work with captcha without captcha users can’t log in. here the source code of index interface.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
		<title>Login With Math Captcha</title>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
	</head>
	<body>
		<br />
		<br />
		<div class="col-md-3"></div>
		<div class="col-md-6 well" style="border:2px solid black;">
			<div class="col-md-3"></div>
			<div class="col-md-6">
				<br />
				<form>
					<div class="form-group">
						<label>Username:</label>
						<input type="text" id="username" class="form-control"/>
					</div>
					<div class="form-group">
						<label>Password:</label>
						<input type="password" id="password" class="form-control"/>
					</div>
					<div class="form-group">
						<label>Captcha:</label>
						<div id="show_captcha"style="font-size:30px; border:2px solid #000;"></div>
						<br />
						<input type="text" id="captcha" class="form-control"/>
					</div>
					<div id="result"></div>
					<br />
					<div class="form-group">
						<button type="button" class="btn btn-success form-control" id="login"> Login</button>
					</div>
				</form>
				<button  class="btn btn-success form-control" data-target="#form_modal" data-toggle="modal">Add User</button>
			</div>
		</div>
		<div class="modal fade" id="form_modal" tabindex="-1" role="dialog" aria-hidden="true" style="border:2px solid #000;">
			<div class="modal-dialog" role="document">
				<form action="save_query.php" method="POST" enctype="multipart/form-data">
					<div class="modal-content">
						<div class="modal-body">
							<div class="col-md-2"></div>
							<div class="col-md-8">
								<div class="form-group">
									<label>Username</label>
									<input class="form-control" type="text" name="username">
									</div>
									<div class="form-group">
										<label>Password</label>
										<input class="form-control" type="password" name="password">
										</div>
										<div class="form-group">
											<label>Name</label>
											<input class="form-control" type="text" name="full_name">
											</div>
										</div>
									</div>
									<div style="clear:both;"></div>
									<div class="modal-footer">
										<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
										<button name="save" class="btn btn-success">Save</button>
									</div>
								</div>
							</form>
						</div>
					</div>
				</body>
				<script src="js/jquery-3.2.1.min.js"></script>
				<script src="js/bootstrap.js"></script>
				<script src="js/script.js"></script>
			</html>

4 – Creating Welcome Page For Login users

in this step, we are going to create a welcome page after user login this page is shown. here the source code of welcome page named home.php

<!DOCTYPE html>
<?php 
	session_start();
	if(!ISSET($_SESSION['user_id'])){
		header('location: index.php');
	}
?>
<html lang="en">
	<head>
		<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
		<title>Login With Math Captcha</title>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
	</head>
	<body>
		<br />
		<br />
		<div class="col-md-3"></div>
		<div class="col-md-6 well" style="border:2px solid black;">
			<?php
			require 'conn.php';
			$query = $conn->query("SELECT * FROM `user` WHERE `user_id` = '$_SESSION[user_id]'");
			$fetch = $query->fetch_array();
		?>
			<h2 class="text-success">Welcome: </h2>
			<h3>
				<?php echo $fetch['name']?>
			</h3>
			<a href="logout.php">Logout</a>
		</div>
	</body>
	<script src="js/jquery-3.2.1.min.js"></script>
</html>

5 – Register user using form and send data into MySQL Database using PHP

in this step, we are going to send user registered data into a MySQL database using PHP script. here the source code of register user in PHP.

<?php
	require_once 'conn.php';
	
	if(ISSET($_POST['save'])){
		$username = $_POST['username'];
		$password = $_POST['password'];
		$full_name = $_POST['full_name'];
		
		if($username == "" || $password == "" || $full_name == ""){
			echo "<script>alert('Please complete the required field!')</scipt>";
			echo "<script>window.location='index.php'</script>";
		}else{
			$conn->query("INSERT INTO `user` VALUES('', '$username', '$password', '$full_name')");
			echo "<script>alert('Successfully created an account')</script>";
			echo "<script>window.location='index.php'</script>";
		}
	}
?>

6 – Validate Login Form using PHP

here we are validating HTML login form using php to user can login using their name and password.

<?php
	session_start();
	require_once 'conn.php';
	$username = $_POST['username'];
	$password = $_POST['password'];
	$captcha = $_POST['captcha'];
	
	if($_SESSION['answer'] == $captcha){
		$query = $conn->query("SELECT * FROM `user` WHERE `username` = '$username' && `password` = '$password'");
		$fetch = $query->fetch_array();
		$rows = $query->num_rows;
		if($rows > 0){
			$_SESSION['user_id'] = $fetch['user_id'];
			echo "success";
		}else{
			echo "error";
		}
	}else{
		echo "captcha";
	}
?>

7 – Creating Logout Function in PHP

in this step, we are destroying the session.

<?php
	session_start();
	session_destroy();
	header('location: index.php');
?>

8 –  Final Step Creating Math CAPTCHA

in this step, we are creating CAPTCHA using PHP & jQUERY. This script includes the creation of captcha and rendering it to the page using jQuery script. The jquery script will send ajax request to the database server and then verified if the user account is already registered.

<?php
	session_start();
	
	$captcha = "";
	$digit1 = rand(1, 100);
	$digit2 = rand(1, 100);
	$array = ["+", "-", "*"];
	$random = array_rand($array);

	switch($array[$random]){
		case "+":
			$_SESSION['captcha'] = $digit1." + ".$digit2;
			$_SESSION['answer'] = $digit1+$digit2;
			break;
		case "-":
			$_SESSION['captcha'] = $digit1." - ".$digit2;
			$_SESSION['answer'] = $digit1-$digit2;
			break;
		case "*":
			$_SESSION['captcha'] = $digit1." * ".$digit2;
			$_SESSION['answer'] = $digit1*$digit2;
			break;
	}
	
	echo "<center>".$_SESSION['captcha']."</center>";
		
?>

script.js – jQuery Script

$(document).ready(function(){	
	$('#show_captcha').load('captcha.php');
	
	$('#login').on('click', function(){
		var username = $('#username').val();
		var password = $('#password').val();
		var captcha = $('#captcha').val();
		
		if(username == "" || password == "" || captcha == ""){
			$('#result').html('<center><label class="text-warning">Please complete the required field!</label></center>');
		}else{
			$.ajax({
				url: 'login.php',
				type: 'POST',
				data: {username: username, password: password, captcha: captcha},
				success: function(data){
					if(data == "captcha"){
						$('#result').html('<center><label class="text-danger">The answer you entered for the CAPTCHA was not correct</label></center>');
						$('#username').val('');
						$('#password').val('');
						$('#captcha').val('')
						$('#show_captcha').load('captcha.php');
					}else if(data == "error"){
						$('#result').html('<center><label class="text-danger">Invalid username or password</label></center>');
						$('#show_captcha').load('captcha.php');
						$('#username').val('');
						$('#password').val('');
						$('#captcha').val('')
					}else if(data == "success"){
						$('#username').val('');
						$('#password').val('');
						$('#captcha').val('');
						window.location = "home.php";
					}
					
				}
			})
		}
	});
});

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Source Code

Categorized in:

JQuery, PHP,