WordPress captcha plugin – building the plugin #1

In today’s post we will start building WordPress captcha plugin. We will show you how to generate captcha image in PHP – this code will be the heart of our captcha plugin. The results of today’s codes can be found here – http://cutecaptcha.itcuties.com/.

ITCuties - WordPress captcha plugin - building the plugin - coding results

ITCuties – WordPress captcha plugin – building the plugin – coding results

Our project structure looks like this.

ITCuties - WordPress captcha plugin - building the plugin - File structure

ITCuties – WordPress captcha plugin – building the plugin – File structure

This is a simple directory structure. images directory contains a reload icon. fonts directory contains a font that we are using to generate captcha sign. We are using tale font which you can find here – http://fontstruct.com/fontstructions/show/760542

captcha.php

This is our main code where we at first create an empty captcha image using imageCreateTrueColor function and set its background pixel colors (imageColorAllocate function) to random values using imageSetPixel function.

Next we write random characters to the image, one by one, using imageTtfText function. Each character has a random size (from 30 to 35 px), angle (from -45° to 45°) and color values. To create a character color the imageColorAllocateAlpha function is used. In the last parameter this function takes an alpha channel value. For each character written, a place where it is going to land in the image has to be calculated separately – take a look at how the $charImageStep and the $charWritePoint are calculated.

At the end, when a captcha image is ready we place captcha text in the session attribute and return the image as a PNG image using imagePng function. In the last line of our code a memory used by generated image is freed – it is done by the imageDestroy function call.


<?php
// Captcha image size
$imageWidth = 300;
$imageHeight= 75;

// Number of characters in captcha image - captcha length
$charsNumber=8;

// Random characters array
$characters=array_merge(range(0,9),range('A','Z'));
// Shuffle the array a little bit :)
shuffle($characters);

// Create captcha image
$captchaImage = imageCreateTrueColor($imageWidth, $imageHeight);

// Set noisy background :) - set random color for each pixel in the image
// For each pixel in the image...
for ( $pixelX=0; $pixelX < $imageWidth; $pixelX++) {
   for ( $pixelY=0; $pixelY < $imageHeight; $pixelY++) {
       // ... generate random pixel color                    // R            // G            // B
       $randomPixelColor = imageColorAllocate($captchaImage, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));

       // Set captcha's background pixel color
       imageSetPixel( $captchaImage, $pixelX, $pixelY , $randomPixelColor);
   }
}

// Captcha text generation
$captchaText = "";    // Full captcha text

// This is the step by which we increase the point of writing each random letter
// to the captcha image.
$charImageStep = $imageWidth/($charsNumber+1);

// Current point in image width where we will write captcha character
$charWritePoint= $charImageStep;

// Write captcha characters to the image
for( $i=0; $i < $charsNumber; $i++) {
   // Get the random character from shuffeled characters array
   $nextChar = $characters[mt_rand(0, count($characters)-1)];
   // join character to captcha string
   $captchaText .= $nextChar;

   // Write next char to image
   // Font properties
   $randomFontSize = mt_rand(30, 35);    // Random character size to spice things a little bit :)
   $randomFontAngle = mt_rand(-45,45);    // Twist the character a little bit
   $fontType = "fonts/tale.ttf";    // This is the font we are using - we need to point to the ttf file here

   // Pixels
   $pixelX = $charWritePoint; // We will write a character at this X point
   $pixelY = mt_rand($imageHeight/2, $imageHeight - $randomFontSize); // We will write a character at this Y point

   // Random character color                                 // R            // G            // B            // Alpha
   $randomCharColor = imageColorAllocateAlpha($captchaImage, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255), mt_rand(0,25));

   // Write a character to the image
   imageTtfText($captchaImage, $randomFontSize, $randomFontAngle, $pixelX, $pixelY, $randomCharColor, $fontType, $nextChar);

   // Increase captcha step
   $charWritePoint += $charImageStep;
}

// Add captcha text to session
session_start();
// Add currently generated captcha text to the session
$_SESSION['captcha'] = $captchaText;

// Return the image
return imagePng($captchaImage);

// Destroy captcha image
imageDestroy($captchaImage);
?>

validate-captcha.php

In this code we validate captcha value sent by user. The value entered by user is read from the associative request array of variables ($_POST['captcha'] value). Correct captcha value is read from the associative session array of variables ($_SESSION['captcha'] value). Next a comparison of those two values is done. Validation is not case-sensitive so the values are turned into the uppercase signs using strToUpper function call. String values are being compared using strCmp function.

<?php
   session_start();
   // Get captcha value from session
   $sessionCaptcha = $_SESSION['captcha'];

   // Get captcha value from request - the one entered by user
   $requestCaptcha = $_POST['captcha'];

   // Validate captcha - char size doesn't matter
   if (strCmp(strToUpper($sessionCaptcha),strToUpper($requestCaptcha)) == 0)
       echo "<div style='color: green'>OK</div>";    // Success
   else
       echo "<div style='color: red'>ERROR, you have entered '".$requestCaptcha."' and the generated captcha was '".$sessionCaptcha."'</div>";    // Error

   // Echo backlink
   echo "<div><a href='/'>back</a></div>";
?>

index.html

This is a simple HTML code which displays captcha image, allows to reload this page to display new captcha image and sends a POST request to validate captcha value.

<html>
   <body>
       <img src="captcha.php">
       <a href=""><img src="images/reload.png"/></a>
       <br/>
       <form action="validate-captcha.php" method="post">
           <input type="text" name="captcha"/>
           <input type="submit" value="validate"/>
       </form>
   </body>
</html>

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW