PHP生成验证码

<?php
session_start();//开启session,必须在脚本顶部

//定义背景图尺寸
$image = imagecreatetruecolor(100,30);
//背景颜色
$bgcolor = imagecolorallocate($image,255,255,255);//#FFFFFFFFFFFF
imagefill($image,0,0,$bgcolor);
$captch_code="";
//循环生成四位验证码
for ($i=0;$i<4;$i++){
//设置字体大小
 $fontsize = 6;
 //字体颜色随机生成
 $fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
 //随机数
 $data='abcdefghijklmnopqrstuvwxyz1234567890';
 $fontcontent=substr($data,rand(0,strlen($data)),1);
 $captch_code.="$fontcontent";
 //设置字间距
 $x = ($i * 100/4)+rand(5,10);
 $y = rand(5,10);
 imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
$_SESSION['code']=$captch_code;//随机生成存储到session中
//增加干扰点
for($i=0;$i<200;$i++){
 $pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
 imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);
}
//增加干扰线
for($i=0;$i<5;$i++){
 $linecolor = imagecolorallocate($image,rand(60,220),rand(60,220),rand(60,220));
 imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
header('content-type: image/png');
imagepng($image);
//销毁
imagedestroy($image);
?>

猜你喜欢

转载自blog.csdn.net/myzhou2017/article/details/80278173