PHP初学笔记-验证码生成

0x01 验证码字符的生成

    新建一个codei.php(图像输出为png格式)

   用dechex()将数字转换成十六进位制(包含字母)

    用session保存可以跨文件调用。

	session_start();
	for($i = 0;$i < 4;$i++){
		if(!isset($_n)){
			$_n = '';
		}
		$_n.= dechex(mt_rand(0,15));
	}

	$_SESSION['code'] = $_n;

0x02 图像的绘制

    简单粗暴的全部复制粘贴了。。。

    注意里面有一个验证码排布的公式

$width  = 100;
	$height = 30;
	$code = imagecreatetruecolor($width,$height);
	header('Content-Type:image/png');
	$white = imagecolorallocate($code,255,255,255);
	$black = imagecolorallocate($code,0,0,0);
	imagefill($code,0,0,$white);																	//填充背景色;
	imagerectangle($code,0,0,$width - 1,$height - 1,$black);										//描绘黑色边线
	for($i = 0;$i < 6;$i++){
		$rand_color = imagecolorallocate($code,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));		//创建随机色
		imageline($code,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$rand_color);//画出干扰线
	}
	
	for($i = 0;$i < 50;$i++){																		//加入噪点
		$rand_color2 = imagecolorallocate($code,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
		imagestring($code,1,mt_rand(1,$width),mt_rand(1,$height),'.',$rand_color2);
	}
	for($i = 0;$i < strlen($_SESSION['code']);$i++){												//将文字加入图片
		$rand_color3 = imagecolorallocate($code,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
	imagestring($code,mt_rand(3,5),$i * $width / 4 + mt_rand(1,$width/4),mt_rand(1,$height/2),$_SESSION['code'][$i],$rand_color3);
}
	imagepng($code);																				//输出图像
	imagedestroy($code);																			//销毁
0x03 单击验证码局部刷新

    新建一个code_index文件

<img src="code.php" οnclick="javascript:this.src='code.php?tm='+Math.random()"/>
    重点是后面的JS代码,控制该区域的局部更新。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值