Monday, February 28, 2011

Simple home made captcha

Hi,

In this post I will give a very basic sample of creating your own captcha, with font, shape and size of your own choice. To achieve this we need the GD library to be enabled for you apache server. In this you need to create two php files and use a ttf file.

First we create the index.php file as follows:



<?php
session_start();
if(isset($_POST['captcha']))
{
if($_POST['captcha']==$_SESSION['captcha_code']){
echo "<font color='green'>Captcha code matched</font>";
}else{
echo "<font color='red'>Incorrect captcha code</font>";
}
echo "<br/>";
}

?>
<form action="" method="post">
<img id="captcha" src="captcha.php" /><br/>
<a href="javascript: void(0)" onclick="document.getElementById('captcha').src='captcha.php'">choose a different word</a>
<br/>
<input type="text" name="captcha" />
<input type="submit" value="Submit">
</form>


Now the second file you need is the captcha.php, which is as follows:
<?php
session_start();
function generateString($length=9, $strength=1) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvzaeuy';
if ($strength == 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength == 2) {
$vowels .= "AEUY";
}
if ($strength == 4) {
$consonants .= '23456789';
}
if ($strength == 8) {
$consonants .= '@#$%';
}
 
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
}
return $password;
}

$time=$_GET['rdId'];

header('Content-type: image/png');
if($time==""){ $time=rand().time(); }
$im = imagecreatetruecolor(140, 40);

$white = imagecolorallocate($im, 250, 250, 250);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 32, 32, 96);
$border_color = imagecolorallocate($im, 128, 128, 128);
imagefilledrectangle($im, 0, 0, 140, 40,$white);

$text = generateString(8,4);
$_SESSION["captcha_code"]=$text;
$font = './cfont.ttf';

for($i=1;$i<=strlen($text);$i++)
{
imagettftext($im, 14, rand(-45,45), ($i*15),22, $black, $font, substr($text,$i-1,1));
}
imagepng($im);
imagedestroy($im);
?>

Now copy and paste a font file of your choice in the same directory as that of captcha.php and rename it to "cfont.ttf". Execute the index.php and your captcha is ready.

To customize your captcha, you can made the necessary modifications in generateString() function.

Best of luck

No comments:

Post a Comment