[TUT] How to create a Captcha image & form

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Earlier on today I create a video-tutorial on how to create your very own captcha image & form, and this is the result:


If you can't be bothered watching the video and just want the code:

index.php
PHP:
<?php
session_start();

if ( isset( $_POST['submit'] ) )
{
$code = strip_tags( $_POST['code'] );
$real_code = $_SESSION['captcha_code'];
if ( $code !== $real_code )
{
echo "Wrong code! Code was {$real_code}";
}
else
{
echo "Correct code!";
}
}
else
{
?>
<form method="post">
<img src="captcha.php" /><br />
Enter code: <input type="text" name="code" /> <input type="submit" name="submit" value="Go" />
</form>
<?php
}
?>

captcha.php
PHP:
<?php
/* This tutorial will teach you how to create your own Captcha image. */

session_start();
$chars = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$length = ( isset( $_GET['l'] ) && is_numeric( $_GET['l'] ) ) ? (int)$_GET['l'] : 8;

$captcha = "";
for ( $i = 1; $i <= $length; $i++ )
{
$captcha .= $chars[ mt_rand( 0, strlen( $chars ) ) ];
}

$_SESSION['captcha_code'] = $captcha;

$width = ( $length * 10 ) - 3;
$img = imagecreate( $width, 17 );
$bg = imagecolorallocate( $img, 0, 0, 0 ); //black
$txt = imagecolorallocate( $img, 255, 255, 255 ); //white
imagestring( $img, 5, 3, 1, $captcha, $txt );

header( "Content-Type: image/PNG" );
imagepng( $img );
imagedestroy( $img );
?>
 

RyanMK

Still alive
May 27, 2010
802
117
Would you mind if I implemented this into tBlogger for comment verification, you'll receive full credits, of course.
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,638
2,393
Would you mind if I implemented this into tBlogger for comment verification, you'll receive full credits, of course.
Yeah sure, I released it with the intention of people using it! :)
 

Users who are viewing this thread

Top