原生php生成验证码

1.原生php生成验证码,如果是框架的话基本上都有验证码的扩展

/**
 * @Explain:	生成验证码
 * @Param:		$type:    标签类型
 */
function captcha($type=1){
	// 开启session
	session_start();
	//1.创建黑色画布
	$image = imagecreatetruecolor(100, 30);
	 
	//2.为画布定义(背景)颜色
	$bgcolor = imagecolorallocate($image, 255, 255, 255);
	 
	//3.填充颜色
	imagefill($image, 0, 0, $bgcolor);
	 
	// 4.设置验证码内容
	 
	//4.1 定义验证码的内容
	if($type = 1){
		$content = "0123456789";
	}else{
		$content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	}
	
	//4.1 创建一个变量存储产生的验证码数据,便于用户提交核对
	$captcha = "";
	for ($i = 0; $i < 4; $i++) {
	    // 字体大小
	    $fontsize = 10;
	    // 字体颜色
	    $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
	    // 设置字体内容
	    $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
	    $captcha .= $fontcontent;
	    // 显示的坐标
	    $x = ($i * 100 / 4) + mt_rand(5, 10);
	    $y = mt_rand(5, 10);
	    // 填充内容到画布中
	    imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
	}
	$_SESSION["captcha"] = $captcha;
	 
	//4.3 设置背景干扰元素
	for ($$i = 0; $i < 200; $i++) {
	    $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
	    imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
	}
	 
	//4.4 设置干扰线
	for ($i = 0; $i < 3; $i++) {
	    $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
	    imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
	}
	 
	//5.向浏览器输出图片头信息
	header('content-type:image/png');
	 
	//6.输出图片到浏览器
	imagepng($image);
	 
	//7.销毁图片
	imagedestroy($image);
}

 2.html调用

<img src="admin/login/captcha.php" onclick="admin/login/captcha.php?'+Math.random();">

3.生成的验证码格式

注:后面拼接的随机数是为了解决部分浏览器点击无法刷新验证码的问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值