CAPTCHA in PHP can help protect your forms from spam and prove they are human.Below step-by-step guide to implementing a simple CAPTCHA system using PHP.
1- Create CAPTCHA Image
captcha.php
<?php
session_start();
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
imagefill($target_layer,0,0,$captcha_background);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");
imagejpeg($target_layer);
?>
2- HTML Form
index.html
<form action="verify.php" method="post">
<label for="captcha">Enter the code shown above:</label><br>
<input type="text" id="captcha" name="captcha"><br>
<img src="captcha.php" alt="CAPTCHA"><br>
<input type="submit" value="Submit">
</form>
3- Verify the CAPTCHA
verify.php
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_input = $_POST['captcha'];
$captcha_code = $_SESSION['captcha_code'];
if ($user_input == $captcha_code) {
echo "Success";
} else {
echo "Failed";
}
}
?>
Step 1- Creates an image with a random string drawn on it, and sends the image to the browser.
Step 2- Creates an HTML form with a text input field for users to enter the CAPTCHA code.And image that display the captcha image generated in captcha.php file.
Step 3- The user's input matches the CAPTCHA code stored in the session variable. If the captcha match it returned success otherwise return fail.