Mecha CMS

Mecha CMS blog and documentation.

Captcha

Updated: Sunday, 07 August 2016

The security captcha.

We have two types of security captcha. Math captcha and image captcha. Both are part of the Guardian class.

Math Captcha

Basic Usage of the Math Captcha

Add this code to your HTML form to add a math captcha verification:

<?php echo Guardian::math(); ?> = <input type="text" name="math">

Then, in your form execution process, check the user’s answer like this:

if(Request::method('post')) {
    if(Guardian::checkMath(Request::post('math'))) {
        echo 'Valid.';
    } else {
        echo 'Invalid.';
    }
}

Math Question Output

echo Guardian::math($min, $max, $text);
ParameterDescription
$minRange minimum of the generated numbers to be randomized.
$maxRange maximum of the generated numbers to be randomized.
$textCustom text output.

Math Answer Checker

Guardian::checkMath($answer);
ParameterDescription
$answerUser input to be compared with the correct answer. Return true on success and false on failure.

Examples:

123 + 388

echo Guardian::math(100, 999);

5 + 10

echo Guardian::math(1, 10);

three plus five

echo Guardian::math(1, 5, array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    '+' => 'plus',
    '-' => 'minus'
));

Image Captcha

Added since version 1.0.3.

Basic Usage of the Image Captcha

Add this code to your HTML form to add an image captcha verification:

<?php echo Guardian::captcha(); ?> = <input type="text" name="answer">

Then, in your form execution process, check the answers of the user like this:

if(Request::method('post')) {
    if(Guardian::checkCaptcha(Request::post('answer'))) {
        echo 'Valid.';
    } else {
        echo 'Invalid.';
    }
}

Captcha Question Output

echo Guardian::captcha($bg, $color, $width, $height, $padding, $size, $length, $font);
ParameterDescription
$bgThe background color. Use hexadecimal color code without leading hash. Change the value to false to create transparent background.
$colorThe text color. Use hexadecimal color code without leading hash.
$widthThe image width.
$heightThe image height.
$paddingThe image padding from text.
$sizeThe text size.
$lengthThe length of the random text to be created.
$fontThe font file name. Change this value to your custom font file name, then upload your custom font to lot\assets\__captcha folder.

Captcha Answer Checker

Guardian::checkCaptcha($answer, $case_sensitive);
ParameterDescription
$answerUser input to be compared with the correct answer. Return true on success and false on failure.
$case_sensitiveMake the captcha answer becomes case insensitive by defining this parameter as false.

Examples:

Captcha Example 1

echo Guardian::captcha();

Captcha Example 2

echo Guardian::captcha(false, '6F7458');

Captcha Example 3

echo Guardian::captcha('5F3333', 'E5B833', 320, 60, 7, 38, 10);
Donation and Email Subscription