PHP用GD库实现简单的验证码

php 用GD库来写验证码 GD库的很多函数 要有一个基本理解

/*4个步骤贯穿整个验证码的逻辑
1,底图的实现  添加干扰元素
2,生成验证内容
3,验证内容保存在服务端
4,验证内容的效验*/

session_start(); // 开启session 为存储验证码做准备

//画布

$image = imagecreatetruecolor(100, 30); // 创建一个宽100 高30的画布

$bgcolor = imagecolorallocate($image, 255, 255, 255); // 为这个画布分配颜色  

imagefill($image, 0, 0, $bgcolor); // 把分配的颜色填充到画布里面


$captch_code = '';

//数字字母组合 来写验证码
for ($i=0; $i <4; $i++) {
	$fontsize = 8; // 设置字体大小
	$fontcolor = imagecolorallocate($image, rand(0,80), rand(0,80), rand(0,80));// 给验证码分配颜色
	$data = 'abcdefghijkmnpqrstuvwxy3456789';// 验证码
		
	$fontcontent = substr($data, rand(0,strlen($data)),1); // 计算出来验证码

	$captch_code .= $fontcontent;
		
	$x = ($i*100/4) + rand(5,10); // X坐标
	$y = rand(5,10); // Y坐标

	imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); // 水平的画一行字符串 即上面得到的验证码
}

	$_SESSION['authcode'] = $captch_code; // 把得到的验证码存放在session中

//干扰点
for ($i=0; $i <300 ; $i++) { // 最多三百个点

	$pointcolor = imagecolorallocate($image, rand(80,220), rand(80,220), rand(80,220)); //分配颜色

	imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor); // 画单一像素

}

//干扰线
for ($i=0; $i <3 ; $i++) {

	$linecolor = imagecolorallocate($image, rand(120,220), rand(120,220), rand(120,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 ); // 销毁图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值