Form captcha

Form can generate spam if they’re not well programmed. A method to block spam is by adding a captcha field. This will generate a (image) code and add it to the session. Every page load the code will be renewed. Visitors must enter the code inside an input field and the submit php code must check the user’s input with the session value.

<?php
session_start();

/*
*    CONFIGURATION
*/

$length = 4;

$color['font'] = 'B62C21';
$color['shadow'] = 'F7A400';
$color['bg'] = '8C0F14';

$font['size'] = 30;
$font['angle'] = 5;
$font['top'] = 38;
$font['left'] = 28;
$font['shadow']['top'] = 2;
$font['shadow']['left'] = 7;
$font['filename'] = 'tahoma_bold.ttf';

$block['width'] = 160;
$block['height'] = 38;

/*
*    START CODE
*/

// function: convert hexadecimal to rgb
function hex2rgb($hexadecimal='',$default=array(255,255,255)) {
    if (!ctype_xdigit($hexadecimal) || strlen($hexadecimal) != 6) {
        return array(255,255,255);
    }
    foreach (str_split($hexadecimal, 2) as $value) {
        $return[] = hexdec($value);
    }
    return $return;
}

// create random number
$start = '1';
$end = '';
for($i=1;$i&lt;=($length-1);$i++) {
    $start .= '0';
}
for($i=1;$i&lt;=$length;$i++) {
    $end .= '9';
}
$random_number = rand($start, $end);
$_SESSION['captcha_code'] = md5($random_number);

// init image
$images = imagecreatetruecolor($block['width'], $block['height']);

// set font colors
$color['font'] = hex2rgb($color['font']);
$color['font'] = imagecolorallocate($images, $color['font'][0],  $color['font'][1], $color['font'][2]);
$color['shadow'] = hex2rgb($color['shadow']);
$color['shadow'] = imagecolorallocate($images,  $color['shadow'][0],$color['shadow'][1],$color['shadow'][2]);
$color['bg'] = hex2rgb($color['bg']);
$color['bg'] = imagecolorallocate($images, $color['bg'][0],  $color['bg'][1], $color['bg'][2]);

// create rectangle
imagefilledrectangle($images, 0, 0, $block['width'], $block['height'],  $color['bg']);

// set font
$font_source = dirName(__FILE__) . '/' . $font['filename'];

// create numbers on rectangle
imagettftext($images, $font['size'], $font['angle'],  ($font['left']+$font['shadow']['left']),  ($font['top']-$font['shadow']['top']), $color['shadow'], $font_source,  $random_number);
imagettftext($images, $font['size'], $font['angle'], $font['left'],  $font['top'], $color['font'], $font_source, $random_number);

// disable cache
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// generate output
header ("Content-type: image/gif");
imagegif($images);
imagedestroy($images);
?>

Leave a Reply

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