captcha_image.php:
session_start();
header('Content-Type: image/png');
$alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
for($i=0; $i<5; $i++) $secret.= $alpha[rand(0,strlen($alpha)-1)];
$_SESSION['secret'] = $secret;
$image = imagecreate(80,31);
$grey = imagecolorallocate($image, 246,246,246);
$red = imagecolorallocate($image, 255, 0, 0);
$color = imagecolorallocate($image, 0, 0, 255);
imagestring($image,5,10,7,$secret,$color);
imageline ($image, 20,0,80,3, $red);
imageline ($image, 0,10,50,0, $red);
imageline ($image, 90,5,40,31, $red);
imageline ($image, 0,31,70,0, $red);
imagepng($image);
imagedestroy($image);
test_ajax.php:
session_start();
if($_POST['secret'] && $_POST['secret'] == $_SESSION['secret']) echo 1;
page.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>Документ без названия</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
</head>
<body>
<img alt="" src="captha_image.php" />
<input id="secret" maxlength="5" type="text" />
<input onclick="test()" type="button" value="Проверить" />
<script type="text/javascript">
function test()
{
$.post('test_ajax.php', {secret: $('#secret').val()}, function(a)
{
alert(a ? 'Всё верно!' : 'Неправильный код безопасности!');
});
}
</script>
</body>
</html>