\Securimage

Securimage CAPTCHA Class.

A class for creating and validating secure CAPTCHA images and audio.

The class contains many options regarding appearance, security, storage of captcha data and image/audio generation options.

Summary

Methods
Properties
Constants
__construct()
getPath()
getCaptchaId()
checkByCaptchaId()
show()
check()
getCaptchaHtml()
getTimeToSolve()
setNamespace()
outputAudioFile()
getCode()
createCode()
getRandomNoiseFile()
frand()
errorHandler()
$image_width
$image_height
$font_ratio
$image_type
$image_bg_color
$text_color
$line_color
$noise_color
$text_transparency_percentage
$use_transparent_text
$code_length
$case_sensitive
$charset
$expiry_time
$session_name
$use_wordlist
$perturbation
$num_lines
$noise_level
$image_signature
$signature_color
$signature_font
$use_sqlite_db
$use_database
$skip_table_check
$database_driver
$database_host
$database_user
$database_pass
$database_name
$database_table
$database_file
$captcha_type
$namespace
$ttf_file
$wordlist_file
$background_directory
$sqlite_database
$audio_path
$audio_use_sox
$sox_binary_path
$audio_noise_path
$audio_use_noise
$audio_mix_normalization
$degrade_audio
$audio_gap_min
$audio_gap_max
$securimage_path
$display_value
SI_IMAGE_JPEG
SI_IMAGE_PNG
SI_IMAGE_GIF
SI_CAPTCHA_STRING
SI_CAPTCHA_MATHEMATIC
SI_CAPTCHA_WORDS
SI_DRIVER_MYSQL
SI_DRIVER_PGSQL
SI_DRIVER_SQLITE3
doImage()
allocateColors()
setBackground()
getBackgroundFromDirectory()
drawWord()
distortedCopy()
drawLines()
drawNoise()
addSignature()
output()
getAudibleCode()
readCodeFromFile()
generateCode()
validate()
saveData()
saveCodeToDatabase()
openDatabase()
getDsn()
checkTablesExist()
createDatabaseTables()
getCodeFromDatabase()
clearCodeFromDatabase()
purgeOldCodesFromDatabase()
isCodeExpired()
generateWAV()
getSoxEffectChain()
getSoxNoiseData()
audioError()
canSendHeaders()
initColor()
$_captchaId
$im
$tmpimg
$bgimg
$iscale
$code
$code_display
$captcha_code
$_timeToSolve
$no_exit
$no_session
$send_headers
$pdo_conn
$gdbgcolor
$gdtextcolor
$gdlinecolor
$gdsignaturecolor
N/A
No private methods found
No private properties found
N/A

Constants

SI_IMAGE_JPEG

SI_IMAGE_JPEG

Constant for rendering captcha as a JPEG image

SI_IMAGE_PNG

SI_IMAGE_PNG

Constant for rendering captcha as a PNG image (default)

SI_IMAGE_GIF

SI_IMAGE_GIF

Constant for rendering captcha as a GIF image

SI_CAPTCHA_STRING

SI_CAPTCHA_STRING

Constant for generating a normal alphanumeric captcha based on the character set

SI_CAPTCHA_MATHEMATIC

SI_CAPTCHA_MATHEMATIC

Constant for generating a captcha consisting of a simple math problem

SI_CAPTCHA_WORDS

SI_CAPTCHA_WORDS

Constant for generating a word based captcha using 2 words from a list

SI_DRIVER_MYSQL

SI_DRIVER_MYSQL

MySQL option identifier for database storage option

SI_DRIVER_PGSQL

SI_DRIVER_PGSQL

PostgreSQL option identifier for database storage option

SI_DRIVER_SQLITE3

SI_DRIVER_SQLITE3

SQLite option identifier for database storage option

Properties

$image_width

$image_width : int

The width of the captcha image

Type

int

$image_height

$image_height : int

The height of the captcha image

Type

int

$font_ratio

$font_ratio : float

Font size is calculated by image height and this ratio. Leave blank for default ratio of 0.4.

Valid range: 0.1 - 0.99.

Depending on image_width, values > 0.6 are probably too large and values < 0.3 are too small.

Type

float

$image_type

$image_type : int

The type of the image, default = png

Type

int

$image_bg_color

$image_bg_color : \Securimage_Color

The background color of the captcha

Type

\Securimage_Color

$text_color

$text_color : \Securimage_Color

The color of the captcha text

Type

\Securimage_Color

$line_color

$line_color : \Securimage_Color

The color of the lines over the captcha

Type

\Securimage_Color

$noise_color

$noise_color : \Securimage_Color

The color of the noise that is drawn

Type

\Securimage_Color

$text_transparency_percentage

$text_transparency_percentage : int

How transparent to make the text.

0 = completely opaque, 100 = invisible

Type

int

$use_transparent_text

$use_transparent_text : bool

Whether or not to draw the text transparently.

true = use transparency, false = no transparency

Type

bool

$code_length

$code_length : int

The length of the captcha code

Type

int

$case_sensitive

$case_sensitive : bool

Whether the captcha should be case sensitive or not.

Not recommended, use only for maximum protection.

Type

bool

$charset

$charset : string

The character set to use for generating the captcha code

Type

string

$expiry_time

$expiry_time : int

How long in seconds a captcha remains valid, after this time it will be considered incorrect.

Type

int

$session_name

$session_name : string

The session name securimage should use.

Only use if your application uses a custom session name (e.g. Joomla). It is recommended to set this value here so it is used by all securimage scripts (i.e. securimage_show.php)

Type

string

$use_wordlist

$use_wordlist : bool

true to use the wordlist file, false to generate random captcha codes

Type

bool

$perturbation

$perturbation : double

The level of distortion.

0.75 = normal, 1.0 = very high distortion

Type

double

$num_lines

$num_lines : int

How many lines to draw over the captcha code to increase security

Type

int

$noise_level

$noise_level : int

The level of noise (random dots) to place on the image, 0-10

Type

int

$image_signature

$image_signature : string

The signature text to draw on the bottom corner of the image

Type

string

$signature_color

$signature_color : \Securimage_Color

The color of the signature text

Type

\Securimage_Color

$signature_font

$signature_font : string

The path to the ttf font file to use for the signature text.

Defaults to $ttf_file (AHGBold.ttf)

Type

string

$use_sqlite_db

$use_sqlite_db : bool

No longer used.

Use an SQLite database to store data (for users that do not support cookies)

Type

bool

$use_database

$use_database : bool

Use a database backend for code storage.

Provides a fallback to users with cookies disabled. Required when using captcha IDs.

Type

bool

$skip_table_check

$skip_table_check : bool

Whether or not to skip checking if Securimage tables exist when using a database.

Turn this to true once database functionality is working to improve performance.

Type

bool — true to not check if captcha_codes tables are set up, false to check (and create if necessary)

$database_driver

$database_driver : string

Database driver to use for database support.

Allowable values: mysql, pgsql, sqlite. Default: sqlite

Type

string

$database_host

$database_host : string

Database host to connect to when using mysql or postgres

On Linux use "localhost" for Unix domain socket, otherwise uses TCP/IP

Does not apply to SQLite

Type

string

$database_user

$database_user : string

Database username for connection (mysql, postgres only) Default is an empty string

Type

string

$database_pass

$database_pass : string

Database password for connection (mysql, postgres only) Default is empty string

Type

string

$database_name

$database_name : string

Name of the database to select (mysql, postgres only)

Type

string

$database_table

$database_table : string

Database table where captcha codes are stored

Note: Securimage will attempt to create this table for you if it does not exist. If the table cannot be created, an E_USER_WARNING is emitted

Type

string

$database_file

$database_file : string

Fully qualified path to the database file when using SQLite3.

This value is only used when $database_driver == sqlite and does not apply when no database is used, or when using MySQL or PostgreSQL.

On *nix, file must have permissions of 0666.

Make sure the directory containing this file is NOT web accessible

Type

string

$captcha_type

$captcha_type : int

The type of captcha to create.

Either alphanumeric based on charset, a simple math problem, or an image consisting of 2 words from the word list.

Type

int

$namespace

$namespace : string

The captcha namespace used for having multiple captchas on a page or to separate captchas from differen forms on your site.

Example:

<?php
// use <img src="securimage_show.php?namespace=contact_form">
// or manually in securimage_show.php
$img->setNamespace('contact_form');

// in form validator
$img->setNamespace('contact_form');
if ($img->check($code) == true) {
    echo "Valid!";
}

Type

string

$ttf_file

$ttf_file : string

The TTF font file to use to draw the captcha code.

Leave blank for default font AHGBold.ttf

Type

string

$wordlist_file

$wordlist_file : string

The path to the wordlist file to use.

Leave blank for default words/words.txt

Type

string

$background_directory

$background_directory : string

The directory to scan for background images, if set a random background will be chosen from this folder

Type

string

$sqlite_database

$sqlite_database : string

No longer used

The path to the SQLite database file to use

Type

string

$audio_path

$audio_path : string

The path to the audio files to be used for audio captchas.

Can also be set in securimage_play.php

Example:

$img->audio_path = '/home/yoursite/public_html/securimage/audio/en/';

Type

string

$audio_use_sox

$audio_use_sox : bool

Use SoX (The Swiss Army knife of audio manipulation) for audio effects and processing.

Using SoX should make it more difficult for bots to solve audio captchas

Type

bool — true to use SoX, false to use PHP

$sox_binary_path

$sox_binary_path : string

The path to the SoX binary on your system

Type

string

$audio_noise_path

$audio_noise_path : string

The path to the directory containing audio files that will be selected randomly and mixed with the captcha audio.

Type

string

$audio_use_noise

$audio_use_noise : bool

Whether or not to mix background noise files into captcha audio

Mixing random background audio with noise can help improve security of audio captcha.

Default: securimage/audio/noise

Type

bool — true = mix, false = no

$audio_mix_normalization

$audio_mix_normalization : float

The method and threshold (or gain factor) used to normalize the mixing with background noise.

See http://www.voegler.eu/pub/audio/ for more information.

Default: 0.6

Valid:

>= 1
Normalize by multiplying by the threshold (boost - positive gain).
A value of 1 in effect means no normalization (and results in clipping).

<= -1
Normalize by dividing by the the absolute value of threshold (attenuate - negative gain).
A factor of 2 (-2) is about 6dB reduction in volume.

[0, 1)  (open inverval - not including 1)
The threshold above which amplitudes are comressed logarithmically.
e.g. 0.6 to leave amplitudes up to 60% "as is" and compressabove.

(-1, 0) (open inverval - not including -1 and 0)
The threshold above which amplitudes are comressed linearly.
e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above.

Type

float

$degrade_audio

$degrade_audio : bool

Whether or not to degrade audio by introducing random noise.

Current research shows this may not increase the security of audible captchas.

Default: true

Type

bool

$audio_gap_min

$audio_gap_min : float

Minimum delay to insert between captcha audio letters in milliseconds

Type

float

$audio_gap_max

$audio_gap_max : float

Maximum delay to insert between captcha audio letters in milliseconds

Type

float

$securimage_path

$securimage_path : string

Absolute path to securimage directory.

This is calculated at runtime

Type

string

$display_value

$display_value : string

Alternate text to draw as the captcha image text

A value that can be passed to the constructor that can be used to generate a captcha image with a given value.

This value does not get stored in the session or database and is only used when calling Securimage::show().

If a display_value was passed to the constructor and the captcha image is generated, the display_value will be used as the string to draw on the captcha image.

Used only if captcha codes are generated and managed by a 3rd party app/library

Type

string — Captcha code value to display on the image

$_captchaId

$_captchaId : string

Captcha ID if using static captcha

Type

string — Unique captcha id

$im

$im : resource

The GD image resource of the captcha image

Type

resource

$tmpimg

$tmpimg : resource

A temporary GD image resource of the captcha image for distortion

Type

resource

$bgimg

$bgimg : resource

The background image GD resource

Type

resource

$iscale

$iscale : int

Scale factor for magnification of distorted captcha image

Type

int

$code

$code : string

The captcha challenge value.

Either the case-sensitive/insensitive word captcha, or the solution to the math captcha.

Type

string — Captcha challenge value

$code_display

$code_display : string

The display value of the captcha to draw on the image

Either the word captcha or the math equation to present to the user

Type

string — Captcha display value to draw on the image

$captcha_code

$captcha_code : string

Captcha code supplied by user [set from Securimage::check()]

Type

string

$_timeToSolve

$_timeToSolve : int

Time (in seconds) that the captcha was solved in (correctly or incorrectly).

This is from the time of code creation, to when validation was attempted.

Type

int

$no_exit

$no_exit : bool

Flag that can be specified telling securimage not to call exit after generating a captcha image or audio file

Type

bool — If true, script will not terminate; if false script will terminate (default)

$no_session

$no_session : bool

Flag indicating whether or not a PHP session should be started and used

Type

bool — If true, no session will be started; if false, session will be started and used to store data (default)

$send_headers

$send_headers : bool

Flag indicating whether or not HTTP headers will be sent when outputting captcha image/audio

Type

bool — If true (default) headers will be sent, if false, no headers are sent

$pdo_conn

$pdo_conn : resource

PDO connection when a database is used

Type

resource

$gdbgcolor

$gdbgcolor : resource

The GD color resource for the background color

Type

resource

$gdtextcolor

$gdtextcolor : resource

The GD color resource for the text color

Type

resource

$gdlinecolor

$gdlinecolor : resource

The GD color resource for the line color

Type

resource

$gdsignaturecolor

$gdsignaturecolor : resource

The GD color resource for the signature text color

Type

resource

Methods

__construct()

__construct(array $options)

Create a new securimage object, pass options to set in the constructor.

The object can then be used to display a captcha, play an audible captcha, or validate a submission.

Parameters

array $options

Options to initialize the class. May be any class property.

$options = array(
    'text_color' => new Securimage_Color('#013020'),
    'code_length' => 5,
    'num_lines' => 5,
    'noise_level' => 3,
    'font_file' => Securimage::getPath() . '/custom.ttf'
);
$img = new Securimage($options);

getPath()

getPath() : string

Return the absolute path to the Securimage directory.

Returns

string —

The path to the securimage base directory

getCaptchaId()

getCaptchaId(bool $new, array $options) : null|string

Generate a new captcha ID or retrieve the current ID (if exists).

Parameters

bool $new

If true, generates a new challenge and returns and ID. If false, the existing captcha ID is returned, or null if none exists.

array $options

Additional options to be passed to Securimage. $options must include database settings if they are not set directly in securimage.php

Returns

null|string —

Returns null if no captcha id set and new was false, or the captcha ID

checkByCaptchaId()

checkByCaptchaId(string $id, string $value, array $options) : bool

Validate a captcha code input against a captcha ID

Parameters

string $id

The captcha ID to check

string $value

The captcha value supplied by the user

array $options

Array of options to construct Securimage with. Options must include database options if they are not set in securimage.php

Returns

bool —

true if the code was valid for the given captcha ID, false if not or if database failed to open

show()

show(string $background_image)

Generates a new challenge and serves a captcha image.

Appropriate headers will be sent to the browser unless the send_headers option is false.

Parameters

string $background_image

The absolute or relative path to the background image to use as the background of the captcha image.

$img = new Securimage();
$img->code_length = 6;
$img->num_lines   = 5;
$img->noise_level = 5;
$img->show(); // sends the image and appropriate headers to browser
exit;

check()

check(string $code) : bool

Checks a given code against the correct value from the session and/or database.

Parameters

string $code

The captcha code to check

$code = $_POST['code'];
$img  = new Securimage();
if ($img->check($code) == true) {
    $captcha_valid = true;
} else {
    $captcha_valid = false;
}

Returns

bool —

true if the given code was correct, false if not.

getCaptchaHtml()

getCaptchaHtml(array $options) : string

Returns HTML code for displaying the captcha image, audio button, and form text input.

Options can be specified to modify the output of the HTML. Accepted options:

'securimage_path':
    Optional: The URI to where securimage is installed (e.g. /securimage)
'image_id':
     A string that sets the "id" attribute of the captcha image (default: captcha_image)
'image_alt_text':
    The alt text of the captcha image (default: CAPTCHA Image)
'show_audio_button':
    true/false  Whether or not to show the audio button (default: true)
'show_refresh_button':
    true/false  Whether or not to show a button to refresh the image (default: true)
'show_text_input':
    true/false  Whether or not to show the text input for the captcha (default: true)
'refresh_alt_text':
    Alt text for the refresh image (default: Refresh Image)
'refresh_title_text':
    Title text for the refresh image link (default: Refresh Image)
'input_id':
    A string that sets the "id" attribute of the captcha text input (default: captcha_code)
'input_name':
    A string that sets the "name" attribute of the captcha text input (default: same as input_id)
'input_text':
    A string that sets the text of the label for the captcha text input (default: Type the text:)
'input_attributes':
    An array of additional HTML tag attributes to pass to the text input tag (default: empty)
'image_attributes':
    An array of additional HTML tag attributes to pass to the captcha image tag (default: empty)
'error_html':
    Optional HTML markup to be shown above the text input field
'namespace':
    The optional captcha namespace to use for showing the image and playing back the audio. Namespaces are for using multiple captchas on the same page.

Parameters

array $options

Array of options for modifying the HTML code.

Returns

string —

The generated HTML code for displaying the captcha

getTimeToSolve()

getTimeToSolve() : int

Get the time in seconds that it took to solve the captcha.

Returns

int —

The time in seconds from when the code was created, to when it was solved

setNamespace()

setNamespace(string $namespace)

Set the namespace for the captcha being stored in the session or database.

Namespaces are useful when multiple captchas need to be displayed on a single page.

Parameters

string $namespace

Namespace value, String consisting of characters "a-zA-Z0-9_-"

outputAudioFile()

outputAudioFile()

Generate an audible captcha in WAV format and send it to the browser with appropriate headers.

Example:

$img = new Securimage();
$img->outputAudioFile(); // outputs a wav file to the browser
exit;

getCode()

getCode(bool $array, bool $returnExisting) : array|string

Return the code from the session or database (if configured). If none exists or was found, an empty string is returned.

Parameters

bool $array

true to receive an array containing the code and properties, false to receive just the code.

bool $returnExisting

If true, and the class property code is set, it will be returned instead of getting the code from the session or database.

Returns

array|string —

Return is an array if $array = true, otherwise a string containing the code

createCode()

createCode()

This method generates a new captcha code.

Generates a random captcha code based on charset, math problem, or captcha from the wordlist and saves the value to the session and/or database.

getRandomNoiseFile()

getRandomNoiseFile() : bool|string

Gets and returns the path to a random noise file from the audio noise directory.

Returns

bool|string —

false if a file could not be found, or a string containing the path to the file.

frand()

frand() : float

Return a random float between 0 and 0.9999

Returns

float —

Random float between 0 and 0.9999

errorHandler()

errorHandler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext) : boolean

The error handling function used when outputting captcha image or audio.

This error handler helps determine if any errors raised would prevent captcha image or audio from displaying. If they have no effect on the output buffer or headers, true is returned so the script can continue processing.

See https://github.com/dapphp/securimage/issues/15

Parameters

int $errno

PHP error number

string $errstr

String description of the error

string $errfile

File error occurred in

int $errline

Line the error occurred on in file

array $errcontext

Additional context information

Returns

boolean —

true if the error was handled, false if PHP should handle the error

doImage()

doImage()

The main image drawing routing, responsible for constructing the entire image and serving it

allocateColors()

allocateColors()

Allocate the colors to be used for the image

setBackground()

setBackground()

The the background color, or background image to be used

getBackgroundFromDirectory()

getBackgroundFromDirectory()

Scan the directory for a background image to use

drawWord()

drawWord()

Draws the captcha code on the image

distortedCopy()

distortedCopy()

Copies the captcha image to the final image with distortion applied

drawLines()

drawLines()

Draws distorted lines on the image

drawNoise()

drawNoise()

Draws random noise on the image

addSignature()

addSignature()

Print signature text on image

output()

output()

Sends the appropriate image and cache headers and outputs image to the browser

getAudibleCode()

getAudibleCode() : string

Generates an audio captcha in WAV format

Returns

string —

The audio representation of the captcha in Wav format

readCodeFromFile()

readCodeFromFile(int $numWords) : string|array

Gets a captcha code from a file containing a list of words.

Seek to a random offset in the file and reads a block of data and returns a line from the file.

Parameters

int $numWords

Number of words (lines) to read from the file

Returns

string|array —

Returns a string if only one word is to be read, or an array of words

generateCode()

generateCode() : string

Generates a random captcha code from the set character set

Returns

string —

A randomly generated CAPTCHA code

validate()

validate()

Validate a code supplied by the user

Checks the entered code against the value stored in the session and/or database (if configured). Handles case sensitivity. Also removes the code from session/database if the code was entered correctly to prevent re-use attack.

This function does not return a value.

saveData()

saveData()

Save CAPTCHA data to session and database (if configured)

saveCodeToDatabase()

saveCodeToDatabase()

Saves the CAPTCHA data to the configured database.

openDatabase()

openDatabase() : bool

Opens a connection to the configured database.

Returns

bool —

true if the database connection was successful, false if not

getDsn()

getDsn() : string

Get the PDO DSN string for connecting to the database

Throws

\Exception

If database specific options are not configured

Returns

string —

The DSN for connecting to the database

checkTablesExist()

checkTablesExist() : boolean

Checks if the necessary database tables for storing captcha codes exist

Throws

\Exception

If the table check failed for some reason

Returns

boolean —

true if the database do exist, false if not

createDatabaseTables()

createDatabaseTables() : boolean

Create the necessary databaes table for storing captcha codes.

Based on the database adapter used, the tables will created in the existing connection.

Returns

boolean —

true if the tables were created, false if not

getCodeFromDatabase()

getCodeFromDatabase() : string|array

Retrieves a stored code from the database for based on the captchaId or IP address if captcha ID not used.

Returns

string|array —

Empty string if no code was found or has expired, otherwise returns array of code information.

clearCodeFromDatabase()

clearCodeFromDatabase()

Remove a stored code from the database based on captchaId or IP address.

purgeOldCodesFromDatabase()

purgeOldCodesFromDatabase()

Deletes old (expired) codes from the database

isCodeExpired()

isCodeExpired(int $creation_time) : bool

Checks to see if the captcha code has expired and can no longer be used.

Parameters

int $creation_time

The Unix timestamp of when the captcha code was created

Returns

bool —

true if the code is expired, false if it is still valid

generateWAV()

generateWAV(array $letters) : string

Generate a wav file given the $letters in the code

Parameters

array $letters

The letters making up the captcha

Returns

string —

The audio content in WAV format

getSoxEffectChain()

getSoxEffectChain(int $numEffects) : string

Get a random effect or chain of effects to apply to a segment of the audio file.

These effects should increase the randomness of the audio for a particular letter/number by modulating the signal. The SoX effects used are bend, chorus, overdrive, pitch, reverb, tempo, and tremolo.

For each effect selected, random parameters are supplied to the effect.

Parameters

int $numEffects

How many effects to chain together

Returns

string —

A string of valid SoX effects and their respective options.

getSoxNoiseData()

getSoxNoiseData(float $duration, int $numChannels, int $sampleRate, int $bitRate) : string

This function is not yet used.

Generate random background noise from sweeping oscillators

Parameters

float $duration

How long in seconds the generated sound will be

int $numChannels

Number of channels in output wav

int $sampleRate

Sample rate of output wav

int $bitRate

Bits per sample (8, 16, 24)

Returns

string —

Audio data in wav format

audioError()

audioError() : string

Return a wav file saying there was an error generating file

Returns

string —

The binary audio contents

canSendHeaders()

canSendHeaders() : bool

Checks to see if headers can be sent and if any error has been output to the browser

Returns

bool —

true if it is safe to send headers, false if not

initColor()

initColor(string $color, \Securimage_Color $default)

Convert an html color code to a Securimage_Color

Parameters

string $color
\Securimage_Color $default

The defalt color to use if $color is invalid