Implement captcha code login validation in PHP with Mysql

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


<?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


// 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


// Include database connection file
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'];
$msg = 'Username or Password Invalid';
$msg = 'Invalid Captcha please try again!';

<!Doctype html>
<html lang="en">
<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="">
<script src=""></script>
<script src=""></script>
<script src=""></script>
<div class="card text-center" style="padding:20px;">
<h3>Implement captcha code login validation in PHP with Mysql</h3>
<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; ?>
<?php } ?>
<form class="form-signin" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="text-center">
<h1>Log In</h1>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" placeholder="Username" required>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password" required>
<div class="form-group">
<a href="<?php echo $_SERVER['PHP_SELF']; ?>"><img src="captcha.php"></a>
<div class="form-group">
<label for="captcha">Captch</label>
<input type="text" class="form-control" name="captcha" placeholder="Captch" required>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary btn-block" value="Sign in">

5. Create User Profile or Dashboard page after login successful


<?phpsession_start();if (isset($_SESSION['NAME'])) {
echo "Hello" . " ". "<b>" . ucwords($_SESSION['NAME']). "</b>";
<p><a href="logout.php">Logout</a></p>

6. Create User Logout page in PHP



Implement captcha code login validation in PHP with Mysql

Originally published at on January 23, 2021.



Webs Codex is programming and web development blog

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store