Jump to content

CAPTCHA/Integration/Images and PHP

From Wikibooks, open books for an open world

image.php

[edit | edit source]
<?php

$width = 50;
$height = 25;

session_start();

unset($_SESSION['code']); // added security

$len = 6; // you can change this
mt_srand(time());
// generate random values
$r = 0;
$g = 0;
$b = 0;
$r = mt_rand(80, 255);
$g = mt_rand(80, 255);
$b = mt_rand(80, 255);

$s = 0;
$h = 0;
$c = 0;
$s = mt_rand(0, 80);
$h = mt_rand(80, 80);
$c = mt_rand(80, 100);

$code = mt_rand(100000,999999);

$size = 0.75 * 40;
$image = imagecreate($width, $height) or die("couldn't generate image");
$bg = imagecolorallocate($image, $s, $h, $c);
$c1 = imagecolorallocate($image, $r, $g, $b);

imagestring($image,2,3,3,$code,$c1);

header('Content-Type: image/png');

imagepng($image);
$_SESSION=$code;
imagedestroy($image);

?>

This is the CAPTCHA itself.

form.php

[edit | edit source]
<?php

echo "<img src='/image.php' /><input name=code />";

?>

This is the form code.

validate.php

[edit | edit source]
<?php

session_start();

if ($_POST['code'] != $_SESSION['code']) {
 //fail
}

?>

This will validate the CAPTCHA.