Tuesday, October 31, 2023

Captcha - PHP GD Library

As Web Application development continues to grow, the need for CAPTCHA is essential. The captcha does it prevents a robot from trying to submit a form on your website.

Prerequisites:

  • A code Editor(Ex. VS Code)
  • Make sure GD(Graphics Draw) library is installed on your host. 

What you need to know about Captcha

On the internet, there are scammers and hackers and they create risky apps to gain access to your app. You may have a lot of problems due to SQL injection, XSS attacks and spam mails.

Spam can increase server load and crash your online application, making it unavailable. Customers or site users are immediately affected. As a result it affects your internet business.

One of the best solutions to this problem is CAPTCHA. It protects against unauthorized access and spam bots. This stops bots from submitting meaningless information through the PHP contact form. Captcha uses a randomly generated code. Runtime production takes place. It appears in various forms.

Here are some examples of popular captcha types:

  • The user has to enter a random number that generates an audio, graphical (image) and text captcha code.
  • Validation ensures that a real human entered the value; In essence, a bot has difficulty filling in a captcha code.  

Registration form with Captcha using PHP GD library

Let's say you have a basic user registration form where they can provide their name, gender and email. 

We are going to implement CAPTCHA. CAPTCHA is mandatory field.Once the user submits the registration form we will validate the form and captcha. 

HTML Contact Form with Captcha

Created a registration form using HTML, CSS and added two captcha fields. One field generates a Captcha image in the other field enter the value from captcha image to pass the validation.

Below is the code snippet for the index.php.

<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
background-color: black;
}

* {
box-sizing: border-box;
}

.container {
max-width: 500px;
margin: 10px auto;
text-align: left;
font-family: sans-serif;
}

form {
border: 1px solid #1A33FF;
background: #ecf5fc;
padding: 5px;
}

input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}

input[type=text]:focus,
input[type=password]:focus {
background-color: #ddd;
outline: none;
}

label {
font-weight: 600;
}

hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}

.registerbtn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}

.registerbtn:hover {
opacity: 1;
}

a {
color: dodgerblue;
}

.signin {
background-color: #f1f1f1;
text-align: center;
}

.form-center {
display: flex;
justify-content: center;
}

.captchaitem {
width: 100%;
display: flex;
flex-direction: row;
}
</style>
</head>

<body>
<div class="form-center">


<form action="/registration.php">
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>

<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="email" required>

<label for="email"><b>Phone</b></label>
<input type="text" placeholder="Enter Email" name="phone" id="phone" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<div class="captchaitem">
<div lass=" col-6">
<label for="email"><b>Captcha</b></label>
<input type="text" placeholder="Enter Captcha" name="captcha" id="captcha" required>
</div>
<div class=" col-6">
<label>Captcha Code</label>
<img src="captcha.php" alt="PHP Captcha">
</div>
</div>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>

<button type="submit" class="registerbtn">Register</button>
</div>

<div class="container signin">
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</div>
</body>

</html>

Creating The Captcha Page

Set the captcha code in the PHP session. Generate a random number with 6 characters.

This will be an output of the security code. Create a basic captcha using the GD library built-in functions. This code will generate the captcha image.

Create captcha.php file and insert the given code in the file.

 
<?php

session_start();
// Generate captcha code
$randomNum = md5(random_bytes(64));
$captchaCode = substr($randomNum, 0, 6);
// Assign captcha in session
$_SESSION['CAPTCHA_CODE'] = $captchaCode;
// Create captcha image
$layer = imagecreatetruecolor(168, 37);
$captchaBg = imagecolorallocate($layer, 207, 104, 71);
imagefill($layer, 0, 0, $captchaBg);
$captchaTextColor = imagecolorallocate($layer, 0, 0, 0);
imagestring($layer, 5, 55, 10, $captchaCode, $captchaTextColor);
header("Content-type: image/jpeg");
imagepng($layer);
imagedestroy($layer);

?>

After running the above snippet, the Interface below is what you will see on the index.php page on your browser.


Captcha validation for the Registration Form

When the user entered the wrong captcha user will also be alerted with a message. Create register.php file and insert the given code in the file.

<?php
session_start();
$captchaError = [];
if ($_POST) {
list('captcha' => $captcha, 'email' => $email, 'password' => $password) = $_POST;

$captchaInput = filter_var($_POST["captcha"], FILTER_DEFAULT);
if (empty($captcha)) {
$captchaError = array(
"status" => "alert-danger",
"message" => "Please enter the captcha."
);
} else if ($_SESSION['CAPTCHA_CODE'] == $captchaInput) {
$captchaError = array(
"status" => "alert-success",
"message" => "Your form has been submitted successfuly."
);
} else {
$captchaError = array(
"status" => "alert-danger",
"message" => "Captcha is invalid."
);
}
}


Include the register.php in the index.php file to bind the captcha with registeration form.

<?php include('register.php'); ?>

<!DOCTYPE html>
<html>

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
background-color: black;
}

* {
box-sizing: border-box;
}

.container {
max-width: 500px;
margin: 10px auto;
text-align: left;
font-family: sans-serif;
}

form {
border: 1px solid #1A33FF;
background: #ecf5fc;
padding: 5px;
}

input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}

input[type=text]:focus,
input[type=password]:focus {
background-color: #ddd;
outline: none;
}

label {
font-weight: 600;
}

hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}

.registerbtn {
background-color: #04AA6D;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}

.registerbtn:hover {
opacity: 1;
}

a {
color: dodgerblue;
}

.signin {
background-color: #f1f1f1;
text-align: center;
}

.form-center {
display: flex;
justify-content: center;
}

.captchaitem {
width: 100%;
display: flex;
flex-direction: row;
}

.captcha-valid {
width: 100%;
display: flex;
}

.alert-success {
background-color: green;
color: #000;
width: 100%;
padding: 5px;
margin: 0 0 10 auto;
}

.alert-danger {
background-color: red;
color: #fff;
width: 100%;
padding: 5px;
margin: 0 0 10 auto;
}
</style>
</head>

<body>
<div class="form-center">

<form method="post">
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<!-- Captcha error message -->
<?php if (!empty($captchaError)) { ?>
<div class="captcha-valid">
<div class="alert text-center <?php echo $captchaError['status']; ?>">
<?php echo $captchaError['message']; ?>
</div>
</div>
<?php } ?>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="email" required>

<label for="email"><b>Phone</b></label>
<input type="text" placeholder="Enter Phone" name="phone" id="phone" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<div class="captchaitem">
<div lass=" col-6">
<label for="email"><b>Captcha</b></label>
<input type="text" placeholder="Enter Captcha" name="captcha" id="captcha" required>
</div>
<div class=" col-6">
<label>Captcha Code</label>
<img src="captcha.php" alt="PHP Captcha">
</div>
</div>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>

<button type="submit" name="submit" class="registerbtn">Register</button>
</div>

<div class="container signin">
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</div>
</body>

</html>

 

Now fill in the fields of the registration form and submit it, it will show success in a green background. But if it’s not successful it will show error message in a red background. 


Conclusion

we successfully created a simple Captcha in PHP and implemented it with the PHP registration form.

No comments:

Post a Comment