<?php
@session_start();
@error_reporting(0);
header('Content-Type: text/html; charset=utf-8');
session_start(); 
//生成验证码图片
header("Content-type: image/png");

// 验证码字符
$str = "a,b,c,d,e,f,j,h,r,y,x,1,2,3,4,5,6,7,8,9,0";      //要显示的字符，可自己进行增删
$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i = 0; $i < 5; $i++ ){
      $randnum = mt_rand(0, $cmax);
      $verifyCode .= $list[$randnum];           //取出字符，组合成为我们要的验证码字符
}
$_SESSION['rand'] = $verifyCode;   //将字符放入SESSION中
 
$im = imagecreate(60,20);    //生成图片
$black = imagecolorallocate($im, rand(0,255),rand(0,255),rand(0,255));     //此条及以下三条为设置的颜色
$white = imagecolorallocate($im, rand(0,100),rand(0,100),rand(0,100));   //背景颜色
$green = imagecolorallocate($im, 0,190,0);
$gray = imagecolorallocate($im, 180,200,200);
$red = imagecolorallocate($im, 190, 0, 0);
imagefill($im,0,0,$white);     //给图片填充颜色
 
//将验证码绘入图片
imagestring($im, 5, 8, 2, $verifyCode, $black);    //将验证码写入到图片中
 
for($i = 0;$i<30;$i++)  //加入干扰象素
{
     imagesetpixel($im, rand(0,48), rand(0,18), $green);    //加入点状干扰素
     imagesetpixel($im, rand(0,48), rand(0,18), $red);
     imagesetpixel($im, rand(0,48), rand(0,18), $gray);
}
imagepng($im);
imagedestroy($im);
?>