Simple Captcha using PHP

Simple Captcha using PHP

Simple Captcha using PHP

As an experienced Web Developer, there will come a time when you will need to implement a Simple Captcha using PHP

Captcha is used to prevent sites from been spammed by spam bots (which will constantly send you irrelevant messages, usually for taking a site), they present an image containing Alphanumeric characters which the users have to enter before successfully posting their input.

In this Post you will learn how to implement a simple Captcha using PHP, you will first create an image using PHP and save in captcha.php file the code below generates an image with random numbers (between 1000 and 4000), a session is first started and the generated numbers are added to the session variable for further validation against user input. After successfully creating the image, you insert the image inside a HTML form as in the code below;

//Start the PHP Session
<?php session_start();
//Create a Random Number between 1000 and 4000
$captchaNumbers = rand(1000,4000);
//save Catcha Number in Session
$_SESSION["captchaNumbers"] = $code;
//Create Image Background of Captcha
$image = @imagecreatefrompng("TheBackgroundImage.png");
//Set Background color of Captcha
$backGroundColor = imagecolorallocate($im, 0, 0, 0); //background color black
//Set text Colour of Captcha
$foreGroundColor = imagecolorallocate($im, 255, 255, 255);//text color white
//Fill the Background with Chosen Image
imagefill($image, 0, 0, $backGroundColor);
//Fill the text with Chosen image
imagestring($image, 5, 5, 5, $captchaNumbers, $foreGroundColor);
//Disable Cache
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
//Set Captcha Background Image to PNG
//Destroy image

Finally you can validate the Captcha response the way you want to, first start session to access $_SESSION[‘captchaNumbers’] variable (that will contain the Random number displayed in the Captcha image) then compare it with posted Captcha response. If both are same then run your code, else exit from code with message Wrong Code Entered

If you have any Questions, please post a comment below