PEAR Packages: Captcha on PHP 2

Tonight, I can’t sleep so I decide to continue writing on the blog… Sorry, long time without activity… I had been concerned about CAPTCHA on gotext’s contact page since I write the last post… Well, I forget about it when I was on my holidays on San Bernardo… But the thing is…

I’m gonna explain how to use it because PEAR captcha documentation is not enough at least for me.

This is the image generated with the program

This is the image generated with the program

The first thing we need to do is find out where is the font we want to use, on ubuntu they are at:

/usr/share/fonts/X11

inside this folder, there are several folders with ttf files inside them, what you can do is copy the  font you want to use into the folder your captcha files will be. Suppose we copy any font but with the name cesar.ttf.

Then we need to create a special file that we will use to insert the image everytime we want. This file will create the session variables to save the captcha word and will print the image. The content of the file can be seen, right here:

<?
require_once ‘Text/CAPTCHA.php’;
session_start();

// Captcha options
$imageOptions = array(
'font_size'        => 20,
'font_path'        => '/var/www/contact_form/',
'font_file'        => 'cesar.ttf',
'text_color'       => '#DDFF99',
'lines_color'      => '#CCEEDD',
'background_color' => '#555555'
);

// Set CAPTCHA options
$options = array(
'width' => 250,
'height' => 100,
'output' => 'png',
'imageOptions' => $imageOptions
);

// Generate a new Text_CAPTCHA object, Image driver
$numcap = Text_CAPTCHA::factory('Image');
$ret = $numcap->init($options);
if (PEAR::isError($ret)) {
printf('Error initializing CAPTCHA: %s!',
$ret->getMessage());
exit;
}

// Get CAPTCHA image (as PNG)
$png = $numcap->getCAPTCHAAsPNG();
if (PEAR::isError($png)) {
echo 'Error generating CAPTCHA!';
echo $png->getMessage();
exit;
}

header("Content-type: image/png");
header("Cookie: PHPSESSID=".session_id());
echo $png;

$_SESSION['answer'] = $numcap->getPhrase();

?>

And here you can see the form example and how we check if the inserted image is correct:

<?php
session_start();

if (isset($_POST['captcha']) && isset($_SESSION['answer'])) {
if ($_POST['captcha'] != $_SESSION['answer']) {
$errors[] = 'Wrong solution! Please, Try Again';
}
}
if (!empty($errors)) {
foreach ($errors as $error) {
print "<h4><font color='red'>$error</font></h4><br />";
}
}
else
{
echo 'You are human!';

}

print '
<form name="capter" action="contact_form.php" method="post">
<table>
<tr>
<th>What is this result?: <img src="contact_form_ic.php" />';
print '</th>
<td><input type="text" value="" name="captcha" /></td>
</tr>
<tr>
<th/>
<td><input type="submit" value="Submit!" /></td>
</tr>
</form>
';
?>

Well... That's all, I hope you can use it and forget about SPAM, or at least... for a little time hehe

Leave a Reply