Implement captcha code login validation in PHP with Mysql

Webs Codex
4 min readJan 23, 2021

This post will explain you, how to make your own custom captcha in PHP using GD library in HTML form. Also look at how to validate the captcha with server-side PHP. Finally, we will also learn how to implement the captcha in the login form.

Do you know what drop is In web development, a captcha is an alphanumeric string randomly generated for the captcha and stored in a session variable which is confirmed by the captcha code entered by the user when filling out form fields.

Captcha is designed to prevent bots or spammers from filling out form fields automatically. Because the captcha code is displayed in an image that can only be read by humans.

If we allow public users to enter data on our website, we must determine that someone has entered that data. Since many users now a days use robots to fill out form data, a lot of unwanted data is entered on the website. So this significantly increases the load on our website and reduces it for the time being.

Therefore, Captcha is a method that website owners can use to prevent robots or bots from inserting data. There are different types of Captcha such as text, audio, or images. We can implement our website and it will dynamically generate random code. The captcha code in the form is mandatory. Without filling in the code, the user cannot submit the form, so the robot cannot read the image text and the robot does not submit form data. If user click on the captcha code it will be change randomly.

Here you only need to take a few steps to proceed.

  1. Create Table In DB by Sql Query.
  2. Create Database Connection PHP File.
  3. Create Captcha using GD library in PHP.
  4. Create User Login Form with Captcha Validation In PHP.
  5. Create User Profile or dashboard page after login successful
  6. Create User Logout page in PHP

2. Create Database Connection PHP File

config.php

<?php	// Database configuration 	
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "webscodex";

// Create database connection
$con = new mysqli($hostname, $username, $password, $dbname);

// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>

3. Create Captcha using GD library in PHP

captcha.php

<?php
session_start();
// Generate a random number
// from 10000-99999
$captcha = rand(10000,99999);
// The capcha will be stored
// for the session
$_SESSION["captcha"] = $captcha;
// Generate a 350x36 standard captcha image
$height = 36;
$width = 350;
$image_p = imagecreate($width, $height);
// Black color
$black = imagecolorallocate($image_p, 0, 0, 0);
// White color
$white = imagecolorallocate($image_p, 255, 255, 255);
// Print the captcha text in the image
// with random position & size
$font_size = 12;
imagestring($image_p, $font_size, 150, 10, $captcha, $white);
imagejpeg($image_p, null, 80); // VERY IMPORTANT: Prevent any Browser Cache!!
header("Cache-Control: no-store, no-cache, must-revalidate");
// The PHP-file will be rendered as image
header('Content-type: image/png');
?>

4.Create User Login Form with Captcha Validation

index.php

<?phpsession_start(); 
// Include database connection file
include_once('config.php');
if (isset($_POST['submit'])) { $username = $con->real_escape_string($_POST['username']);
$password = $con->real_escape_string(md5($_POST['password']));
$msg = '';
// If the captcha is valid
if ($_POST['captcha'] == $_SESSION['captcha']) {
$query = "SELECT * FROM admins WHERE username = '$username' AND password ='$password'"; $result = $con->query($query);

$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
$_SESSION['NAME'] = $row['name'];
header("Location:dashboard.php");
die();
}else{
$msg = 'Username or Password Invalid';
}
}else{
$msg = 'Invalid Captcha please try again!';
}
}

?>
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Implement captcha code login validation in PHP with Mysql</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="card text-center" style="padding:20px;">
<h3>Implement captcha code login validation in PHP with Mysql</h3>
</div><br>
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<!-- Error message -->
<?php if (isset($msg)) { ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $msg; ?>
</div>
<?php } ?>
<form class="form-signin" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="text-center">
<h1>Log In</h1>
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username" required>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" required>
</div>
<div class="form-group">
<a href="<?php echo $_SERVER['PHP_SELF']; ?>"><img src="captcha.php"></a>
</div>
<div class="form-group">
<label for="captcha">Captch</label>
<input type="text" class="form-control" name="captcha" placeholder="Captch" required>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary btn-block" value="Sign in">
</div>
</form>
</div>
</div>
</div>
</body>
</html>

5. Create User Profile or Dashboard page after login successful

dashboard.php

<?phpsession_start();if (isset($_SESSION['NAME'])) {
echo "Hello" . " ". "<b>" . ucwords($_SESSION['NAME']). "</b>";
}else{
header("Location:login.php");
die();
}
?>
<br><br>
<p><a href="logout.php">Logout</a></p>

6. Create User Logout page in PHP

logout.php

<?php
session_start();
session_destroy();
unset($_SESSION['NAME']);
header("Location:index.php");
?>

Implement captcha code login validation in PHP with Mysql

Originally published at https://www.webscodex.com on January 23, 2021.

--

--

Webs Codex

Webs Codex is programming and web development blog