Creating Login Script With Math Captcha Using PHP and jQuery

In this tutorial we will create a Login Script With Math Captcha Using jQuery. PHP is a server-side scripting language designed primarily for web development. Using PHP, you can let your user directly interact with the script and easily to learned its syntax. Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page.

So Let's do the coding...

Before we get started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html.

And this is the link for the jquery that i used in this tutorial https://jquery.com/.

Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_captcha. After that, click Import then locate the database file inside the folder of the application then click ok.

tut1

To create the sample table and data, copy the code below and paste it into the SQL tab of your newly created database in PHPMyAdmin.

  1. CREATE TABLE `user` (
  2. `username` varchar(20) NOT NULL,
  3. `password` varchar(12) NOT NULL,
  4. `name` varchar(50) NOT NULL
  5.  
  6. INSERT INTO `user` (`user_id`, `username`, `password`, `name`) VALUES
  7. (1, 'admin', 'admin', 'Administrator');

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'db_captcha');
  3.  
  4. if(!$conn){
  5. die("Error: Failed to connect to database!");
  6. }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write them into your text editor, then save them as shown below.

index.php
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Login Script WIth Math Captcha using jQuery</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <div class="col-md-3"></div>
  18. <div class="col-md-6">
  19. <button class="btn btn-primary" data-target="#form_modal" data-toggle="modal"><span class="glyphicon glyphicon-plus"></span> Add User</button>
  20. <br />
  21. <br />
  22. <form>
  23. <div class="form-group">
  24. <label>Username:</label>
  25. <input type="text" id="username" class="form-control"/>
  26. </div>
  27. <div class="form-group">
  28. <label>Password:</label>
  29. <input type="password" id="password" class="form-control"/>
  30. </div>
  31. <div class="form-group">
  32. <label>Captcha:</label>
  33. <div id="show_captcha"style="font-size:40px; border:2px solid #000;"></div>
  34. <br />
  35. <input type="text" id="captcha" vclass="form-control"/>
  36. </div>
  37. <div id="result"></div>
  38. <br />
  39. <div class="form-group">
  40. <button type="button" class="btn btn-primary form-control" id="login"><span class="glyphicon glyphicon-log-in"></span> Login</button>
  41. </div>
  42. </form>
  43. </div>
  44. </div>
  45. <div class="modal fade" id="form_modal" tabindex="-1" role="dialog" aria-hidden="true">
  46. <div class="modal-dialog" role="document">
  47. <form action="save_query.php" method="POST" enctype="multipart/form-data">
  48. <div class="modal-content">
  49. <div class="modal-body">
  50. <div class="col-md-2"></div>
  51. <div class="col-md-8">
  52. <div class="form-group">
  53. <label>Username</label>
  54. <input class="form-control" type="text" name="username">
  55. </div>
  56. <div class="form-group">
  57. <label>Password</label>
  58. <input class="form-control" type="password" name="password">
  59. </div>
  60. <div class="form-group">
  61. <label>Name</label>
  62. <input class="form-control" type="text" name="full_name">
  63. </div>
  64. </div>
  65. </div>
  66. <div style="clear:both;"></div>
  67. <div class="modal-footer">
  68. <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  69. <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  70. </div>
  71. </div>
  72. </form>
  73. </div>
  74. </div>
  75. </body>
  76. <script src="js/jquery-3.2.1.min.js"></script>
  77. <script src="js/bootstrap.js"></script>
  78. <script src="js/script.js"></script>
  79. </html>
home.php
  1. <!DOCTYPE html>
  2. <?php
  3. if(!ISSET($_SESSION['user_id'])){
  4. header('location: index.php');
  5. }
  6. ?>
  7. <html lang="en">
  8. <head>
  9. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  10. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  11. </head>
  12. <body>
  13. <nav class="navbar navbar-default">
  14. <div class="container-fluid">
  15. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  16. </div>
  17. </nav>
  18. <div class="col-md-3"></div>
  19. <div class="col-md-6 well">
  20. <h3 class="text-primary">PHP - Login Script WIth Math Captcha using jQuery</h3>
  21. <hr style="border-top:1px dotted #ccc;"/>
  22. <?php
  23. require 'conn.php';
  24. $query = $conn->query("SELECT * FROM `user` WHERE `user_id` = '$_SESSION[user_id]'");
  25. $fetch = $query->fetch_array();
  26. ?>
  27. <h2 class="text-primary">Welcome: </h2><h3><?php echo $fetch['name']?></h3>
  28. <a href="logout.php">Logout</a>
  29. </div>
  30. </body>
  31. <script src="js/jquery-3.2.1.min.js"></script>
  32. </html>

Creating PHP Script

This code contains the PHP query of the application. This code is consists of several functionalities, it includes login, logout, and creating an account. To do that just copy and write this block of codes inside the text editor, then save it as shown below. save_query.php
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['save'])){
  5. $username = $_POST['username'];
  6. $password = $_POST['password'];
  7. $full_name = $_POST['full_name'];
  8.  
  9. if($username == "" || $password == "" || $full_name == ""){
  10. echo "<script>alert('Please complete the required field!')</scipt>";
  11. echo "<script>window.location='index.php'</script>";
  12. }else{
  13. $conn->query("INSERT INTO `user` VALUES('', '$username', '$password', '$full_name')");
  14. echo "<script>alert('Successfully created an account')</script>";
  15. echo "<script>window.location='index.php'</script>";
  16. }
  17. }
  18. ?>
login.php
  1. <?php
  2.  
  3. require_once 'conn.php';
  4.  
  5. $username = $_POST['username'];
  6. $password = $_POST['password'];
  7. $captcha = $_POST['captcha'];
  8.  
  9. if($_SESSION['answer'] == $captcha){
  10. $query = $conn->query("SELECT * FROM `user` WHERE `username` = '$username' && `password` = '$password'");
  11.  
  12. $fetch = $query->fetch_array();
  13. $rows = $query->num_rows;
  14.  
  15. if($rows > 0){
  16. $_SESSION['user_id'] = $fetch['user_id'];
  17. echo "success";
  18. }else{
  19. echo "error";
  20. }
  21.  
  22. }else{
  23. echo "captcha";
  24. }
  25.  
  26.  
  27.  
  28.  
  29. ?>
logout.php
  1. <?php
  2. header('location: index.php');
  3. ?>

Creating the Captcha Script

This section contains the main function of the application. This script includes the creation of a captcha and rendering it to the page using jQuery script. The jquery script will send an Ajax request to the database server and then verified if the user account is already registered. To do that just kindly follow the code and write these inside your text editor, then save it as follows: captcha.php
  1. <?php
  2.  
  3. $captcha = "";
  4. $digit1 = rand(1, 100);
  5. $digit2 = rand(1, 100);
  6. $array = ["+", "-", "*"];
  7. $random = array_rand($array);
  8.  
  9. switch($array[$random]){
  10. case "+":
  11. $_SESSION['captcha'] = $digit1." + ".$digit2;
  12. $_SESSION['answer'] = $digit1+$digit2;
  13. break;
  14. case "-":
  15. $_SESSION['captcha'] = $digit1." - ".$digit2;
  16. $_SESSION['answer'] = $digit1-$digit2;
  17. break;
  18. case "*":
  19. $_SESSION['captcha'] = $digit1." * ".$digit2;
  20. $_SESSION['answer'] = $digit1*$digit2;
  21. break;
  22. }
  23.  
  24. echo "<center>".$_SESSION['captcha']."</center>";
  25.  
  26. ?>
script.js
  1. $(document).ready(function(){
  2. $('#show_captcha').load('captcha.php');
  3.  
  4. $('#login').on('click', function(){
  5. var username = $('#username').val();
  6. var password = $('#password').val();
  7. var captcha = $('#captcha').val();
  8.  
  9. if(username == "" || password == "" || captcha == ""){
  10. $('#result').html('<center><label class="text-warning">Please complete the required field!</label></center>');
  11. }else{
  12. $.ajax({
  13. url: 'login.php',
  14. type: 'POST',
  15. data: {username: username, password: password, captcha: captcha},
  16. success: function(data){
  17. if(data == "captcha"){
  18. $('#result').html('<center><label class="text-danger">The answer you entered for the CAPTCHA was not correct</label></center>');
  19. $('#username').val('');
  20. $('#password').val('');
  21. $('#captcha').val('')
  22. $('#show_captcha').load('captcha.php');
  23. }else if(data == "error"){
  24. $('#result').html('<center><label class="text-danger">Invalid username or password</label></center>');
  25. $('#show_captcha').load('captcha.php');
  26. $('#username').val('');
  27. $('#password').val('');
  28. $('#captcha').val('')
  29. }else if(data == "success"){
  30. $('#username').val('');
  31. $('#password').val('');
  32. $('#captcha').val('');
  33. window.location = "home.php";
  34. }
  35.  
  36. }
  37. })
  38. }
  39. });
  40. });
DEMO

There you have it we successfully created Login Script With Math Captcha Using jQuery. I hope that this simple tutorial helps you to what you are looking for. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!!

Add new comment