PHP - Login Script With Math Captcha Using jQuery

Submitted by: 
Language: 
Visitors have accessed this post 539 times.

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

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

Creating PHP Script

This code contains the php query of the application. This code is consist of several functionalities, it includes the 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 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. 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. });

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


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.