php验证码


先创建一个demo.php;
<img src="imgcode.php" onclick="this.src = 'imgcode.php?num='+new Date().getTime();" />
然后创建一个imgcode.php
<?phpfunction get_rand_str($length = 4)
{
    $chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZ';
    $str = str_shuffle($chars); // 随机打乱一个字符串
    $str = substr($str,0,$length);
    $str = strtolower($str);
    return $str;
}//验证码图片宽度和高度
$width = 45;
$height = 18;

//新建一张彩色图片
$img = imagecreatetruecolor($width,$height);

//给这张图片新建两个颜色 

//背景颜色
$backgroundcolor = imagecolorallocate($img,74,147,223);

//文字颜色
$textcolor = imagecolorallocate($img,255,255,255);//画一矩形并填充   $width,$height, 对角线
imagefilledrectangle($img,0,0,$width,$height,$backgroundcolor);

//获取随机数
$get_code = get_rand_str(); //获取出来的随机数写到图片上面
imagestring($img,5,6,1,$get_code,$textcolor);//防止别人恶意刷验证码在图片上面添加一些点
for($i=0;$i<=20;$i++)
{
    $x = mt_rand(0,$width);
    $y = mt_rand(0,$height);
    $pxColor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
    imagesetpixel($img,$x,$y,$pxColor);
}//写一个输出图片的声明头信息
header("Content-Type:image/png");

imagepng($img);

//输出完成后销毁
imagedestroy($img);
?>

原文地址:https://www.cnblogs.com/qixidi/p/10202482.html