In this tutorial, we are going to learn how to create a random captcha generator. In the HTML using a form tag creating a register form.
Most of the time the allowing users are entering into a website or registering data into our website.
We just need to know the users are bots or humans. If the bots are easy to insert the bulk of records without permission and push in the database.
sometimes the bots are inserted malicious file to access hackers like SQL injection and the process make a lot of problem on our website.
Captcha is the only way to filter the humans and bots prevent access before sending data.
For example, Create a random captcha generate code.
Here, I have created a contact form using HTML and PHP to manage captcha sessions.
HTML create a input tag and named as Name, Email, Mobile No, Gender.
In the HTML select tags are performs option method and when client-side selected the option and it's in array method and using of foreach method to get the exact selected option to store data in the SQL database.
Read also: File Upload using PHP
Create Database Table
create table register
(
id int auto_increment primary key,
name varchar(50) not null,
email varchar(50) not null,
gender varchar(50) not null,
mobile varchar(15) not null
);
Index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manual Captcha code Generator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<center>
<h2>Manual Captcha code Generator</h2>
</center>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="email">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-select" name="gender[]">
<option selected>Select</option>
<option value="male">Male</option>
<option value="Female">Female</option>
<option value="Trans">Transgender</option>
</select>
</div>
<div class="form-group">
<label>Mobile no.</label>
<input type="text" class="form-control" name="mobile" id="number">
</div>
<div class="row ls">
<div class="form-group col-6">
<label>Enter Captcha</label>
<input type="text" class="form-control" name="captcha" id="captcha">
</div>
<div class="form-group col-6">
<label>Captcha Code</label>
<img src='js/captcha.php' alt="PHP Captcha">
</div>
</div>
<div class="d-grid gap-2 col-6 mx-auto">
<input type="submit" name="submit" value="submit" class="btn btn-primary btn-block">
</div>
</form>
</div>
</body>
</html>
Connect with Database dbconfig.php
<?php
$hostname = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$hostname;dbname=studentdb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Database connected successfully";
} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
?>
Style.css
body{
background-color:fefefe;
}
.container
{
max-width:500px;
text-align: left;
font-family: sans-serif;
}
form {
border: 1px solid #333;
background: #ffffff;
padding: 40px 50px 45px;
}
.form-group
{
padding:.75rem !important;
}
.ls, .form-group
{
padding:.75rem !important;
}
Contact-form.php
<?php include 'js/dbconfig.php'; ?>
<?php
session_start();
if (isset($_POST["submit"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$mobile = $_POST["mobile"];
if (!empty($_POST['gender'])) {
foreach ($_POST['gender'] as $selected) {
$gender = $selected;
}
} else {
echo 'Please select the option.';
}
$captcha = $_POST["captcha"];
$captchaUser = filter_var($_POST["captcha"], FILTER_SANITIZE_STRING);
if (empty($captcha)) {
$captchaError = [
"status" => "alert-danger",
"message" => "Please enter the captcha.",
];
} elseif ($_SESSION['CAPTCHA_CODE'] == $captchaUser) {
$insert_stmt = $conn->prepare('INSERT INTO register(name,email,gender,mobile) VALUES(:name,:email,:gender,:mobile)');
$insert_stmt->bindParam(':name', $name, PDO::PARAM_STR);
$insert_stmt->bindParam(':email', $email, PDO::PARAM_STR);
$insert_stmt->bindParam(':gender', $gender, PDO::PARAM_STR);
$insert_stmt->bindParam(':mobile', $mobile, PDO::PARAM_STR);
$insert_stmt->execute();
$captchaError = [
"status" => "alert-success",
"message" => "Your form has been submitted successfuly.",
];
} else {
$captchaError = [
"status" => "alert-danger",
"message" => "Captcha is invalid.",
];
}
}
?>
Captcha.php
Imagefill() is an in-built function that is function is used to fill the given color. and it performs a flood fill starting on four-parameter and given coordinates .fill the coordinates top left is (0,0) to give color.
The background code to get the captcha randomly to create an image source and the function are check the captcha user are enter and return the browser to save the records.
syntax:
imagefill( $image,$x,$y,$color);
- $image - It's returned one of the image creation such as using of function imagecreatetruecolor();
- $x- start point of x-coordinate
- $y- Start point of y-coordinate
- $color= fill color with identifier of imagecolorallocate().
Here, in this below code, I just created random bytes used of md5, and the session returns the image string must be equal by the user enter code.
imagestring($image,$font,$x,$y, string $string,$color);
$font- Fonts parameter is inbuilt encoding can be used 1 to 5.
And finally specifies header with image/png. return image using of imagepng();
<?php
session_start();
$random_num = md5(random_bytes(64));
$captcha_code = substr($random_num, 0, 8);
$_SESSION['CAPTCHA_CODE'] = $captcha_code;
$color_rec = imagecreatetruecolor(170, 38);
$captcha_bg = imagecolorallocate($color_rec, 105, 105, 105);
imagefill($color_rec, 0, 0,$captcha_bg);
$text_color = imagecolorallocate($color_rec, 255, 255,255);
imagestring($color_rec, 5, 55, 10, $captcha_code, $text_color);
header("Content-type: image/png");
imagepng($color_rec);
?>
It may error occur in the random Captcha generator using of Bootstrap enable error top of the form table. Just Insert the code below the body tags.
<div class="container mt-5">
<?php include 'contact-form.php'; ?>
<?php if (!empty($captchaError)) { ?>
<div class="form-group col-12 text-center">
<div class="alert text-center <?php echo $captchaError['status']; ?>">
<?php echo $captchaError['message']; ?>
</div>
</div>
<?php } ?>
Random Captcha Generator Full Code
<?php include 'js/dbconfig.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Manual Captcha code Generator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<center><h2>Manual Captcha code Generator</h2></center>
<div class="container mt-5">
<?php include 'contact-form.php'; ?>
<?php if (!empty($captchaError)) { ?>
<div class="form-group col-12 text-center">
<div class="alert text-center <?php echo $captchaError['status']; ?>">
<?php echo $captchaError['message']; ?>
</div>
</div>
<?php } ?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name" />
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" id="email" />
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-select" name="gender[]">
<option selected>Select</option>
<option value="male">Male</option>
<option value="Female">Female</option>
<option value="Trans">Transgender</option>
</select>
</div>
<div class="form-group">
<label>Mobile no.</label>
<input type="text" class="form-control" name="mobile" id="number" />
</div>
<div class="row ls">
<div class="form-group col-6">
<label>Enter Captcha</label>
<input type="text" class="form-control" name="captcha" id="captcha" />
</div>
<div class="form-group col-6">
<label>Captcha Code</label>
<img src="js/captcha.php" alt="PHP Captcha" />
</div>
</div>
<div class="d-grid gap-2 col-6 mx-auto">
<input type="submit" name="submit" value="submit" class="btn btn-primary btn-block" />
</div>
</form>
</div>
</body>
</html>
In this tutorial, we have created a random captcha generator that is integrated with the PHP contact form. In the logic create a Captcha to make a solution for users. We have simply told the visitors to check the input captcha if that they entered an incorrect captcha the process is repeated. If you have any questions or suggestions on the comment. we will look at it and make it soon..!