跳转到内容

CAPTCHA/集成/图像和PHP

来自维基教科书,开放的书,为开放的世界

image.php

[编辑 | 编辑源代码]
<?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);

?>

这是CAPTCHA本身。

<?php

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

?>

这是表单代码。

validate.php

[编辑 | 编辑源代码]
<?php

session_start();

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

?>

这将验证CAPTCHA。

华夏公益教科书