yzm.php
<?php
//生成验证码图片
session_start();
Header("Content-type: p_w_picpath/gif");
srand((double)microtime()*1000000);
$im = p_w_picpathcreate(45,18);//设置图片的宽与高
$black = ImageColorAllocate($im, 0,0,0);//设置背景颜色
$white = ImageColorAllocate($im, 255,255,255);//设置文字颜色
$gray = ImageColorAllocate($im, 200,200,200);//干扰颜色
p_w_picpathfill($im,45,18,$gray);
while(($chk_num=rand()%10000)<1000);
$_SESSION["chk_num"] = $chk_num;
//将四位整数验证码绘入图片
p_w_picpathstring($im, 5, 5, 1,$chk_num , $white);//5, 5, 1分别表示为字体大小,左边距,上边距
for($i=0;$i<100;$i++) //加入干扰象素
{
p_w_picpathsetpixel($im, rand()%70 , rand()%30 , $gray);
}
ImagePNG($im);
ImageDestroy($im);
?>


yanzhengma.php
<html>
<head>
<title>验证码判断</title>
</head>
<body>
<form method="post" action="yanzhengma.php">
<input type="text" name="yzm" >
<img src="yzm.php" ><br>
<input type="submit" name="submit" value="验证">
<?php
error_reporting(0);

session_start();

if (isset($_POST['submit']))
{
  echo "<br>".$_SESSION[yzm];
  echo "<br>".$_POST['yzm'];

  if ($_POST['yzm'] == $_SESSION[yzm])
  {
  echo "<br>"."OK!";
  }
  else
  {
  echo "<br>"."NO!";
  }
}
?>

</form>
</body>
</html>