sFire PHP Framework

Captcha

A Captcha (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart") is a type of challenge-response test used in computing to determine whether or not the user is human. It can prevent automated form submits which can be important for registration forms for example.

sFire\System\Captcha is a handy tool for generating captcha images for securing forms.

Note: for this captcha class to work, you should enable imagettfbbox.

In this section we will handle

  • Creating new instance
  • Set a background image
  • Set font, font color and font size
  • Set and retrieve captcha characters
  • Generate captcha

Creating new instance

To use the sFire captcha class, you can create a new instance by doing:

use sFire\System\Captcha;

$captcha = new Captcha();

Set a background image

You can use the setImage method to set a new background image. This image should be a JPG, JPEG or PNG file. This image will be used to generate the captcha characters on top of it and is required to be set.

$captcha = new Captcha();
$captcha -> setImage('path/to/captcha/background.png');

Set font, font color and font size

With the setFont method, you can set the font of the captcha characters. You can use ttf and woff fonts. The setFontColor method accepts RGB values or Hexadecimal and will set the color of the captcha characters. With the setFontSize method, you can set the size of the font in pixels.

$captcha = new Captcha();

//Accepts woff or ttf
$captcha -> setFont('path/to/font.ttf');

//RGB values
$captcha -> setFontColor(50, 138, 62);

//Hexdecimal value
$captcha -> setFontColor('#06Fe4C');

//Set the font size
$captcha -> setFontSize(30);

Set and retrieve captcha characters

The captcha class can generate a text for you, but you can also set the text manually by calling the setText method. The generateText method will generate random characters without using characters that look the same, for example the "0" and "o" or "9" and "g".

$captcha = new Captcha();

//Set a random text
$captcha -> setText('B52kH');

You can also generate the text with the generateText method.

//Generate text with 5 characters (default)
$captcha -> setText($captcha -> generateText());

//Generate text with 8 characters
$captcha -> setText($captcha -> generateText(8));

You can then retrieve the text (for validation) with the getText method.

$text = $captcha -> getText();
echo $text; //Outputs similar to "B52kH"

Generate captcha

You can either generate the captcha to be displayed as a image directory into the browser, or you can save the captcha to a file using the generate method.

$captcha = new Captcha();

//Display the captcha directory into the browser
$captcha -> generate();

//Or save the captcha as a file
$captcha -> generate('path/for/saving/captcha.png');