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.

Implement captcha code login validation in PHP with Mysql

Create Table In Database by Sql Query.

-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `admins`

CREATE TABLE `admins` (
  `name` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()

Create Database Connection PHP File



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


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'); 


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'];
        } else {
            $msg = 'Username or Password Invalid';
    } else {
        $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">


Create User Profile or Dashboard page after login successful




if (isset($_SESSION['NAME'])) {
    echo "Hello" . "  ". "<b>" . ucwords($_SESSION['NAME']). "</b>";		

<p><a href="logout.php">Logout</a></p>

Create User Logout page in PHP



You can always support by sharing on social media or recommending my blog to your friends and colleagues.   If you have any suggestions or problems about this tutorial, please comment on the  form below.😊

Implement captcha code login validation in PHP with Mysql

Leave a Reply

Your email address will not be published. Required fields are marked *