PHP的验证码

在开发网站的过程中,验证码应该是表单里时常需要的一个功能块,可是说起GD库函数,那真是长,不对照手册,根本记不住。所以抽出时间总结了一下,以后也好重复利用,提高效率,若是其中有不完善的地方,还望各位前辈及大神指出~~

<?php
/**
* 构造方法用来实例化验证码对象
* @author xiaohuixiong
* @version 版本1.0 | 2013-11-05 
* @param int $codeNum | 验证码中字符个数,默认为4个
* @param int $width | 验证码图片宽度,默认为80像素
* @param int $height | 验证码图片高度,默认为25像素 
**/

vcode();

function vcode($codeNum=4, $width=80, $height=25){

	//获取随机的验证码串
	$code = getCode($codeNum);
	//创建一个画布
	$im = imagecreatetruecolor($width, $height);
	//创建要用到的颜色
	$backgroundColor = imagecolorallocate($im, 255, 255, 255);
	$borderColor = imagecolorallocate($im, 200, 200, 200);
	//画背景
	imagefilledrectangle($im, 0, 0, $width, $height,$backgroundColor);
	//画边框
	imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
	//画干扰点
	for($i=0; $i<50; $i++){
		$pointColor = imagecolorallocate($im, rand(0,128), rand(0,128), rand(0,128));
		imagesetpixel($im, rand(0,$width), rand(0,$height), $pointColor);
	}
	//画干扰线
	for($i=0; $i<5; $i++){
		$lineColor = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
		imagearc($im, mt_rand(-$width,$width), mt_rand(-$height,$height), mt_rand(30,$width), mt_rand(20,$height), mt_rand(0,360), mt_rand(0,360), $lineColor);
	}
	//画字符
	for($i=0; $i<strlen($code); $i++){
		$fontColor = imagecolorallocate($im, rand(0,128), rand(0,128), rand(0,128));
		$fontSize = rand(18,24);
		$x = floor($width/$codeNum)*$i+3;
		$y = rand(0,$height-$fontSize);
		imagechar($im, $fontSize, $x, $y, $code[$i], $fontColor);
	}
	//将随机的字符存入SESSION
	$_SESSION['vcode'] = $code;
	//输出图像
	outImg($im);
	//销毁图像资源(释放内存)
	imagedestroy($im);
	exit;
}

//获取验证码串
function getCode($codeNum){
	$str = "3456789abcdefghjkmnpkrstuvwxyABCDEFGHJKMNPQRSTUVWXY";
	$code = "";
	for($k=0; $k<$codeNum; $k++){
		$code.= $str[rand(0,strlen($str)-1)];
	}
	return $code;
}
//检测GD支持的图像类型,并输出图像
function outImg($im){
	if(imagetypes() & IMG_PNG){
		header("Content-Type: image/png");
		imagepng($im);
	}elseif(imagetypes() & IMG_JPG){
		header("Content-Type: image/jpeg");
		imagejpeg($im);
	}elseif(imagetypes() & IMG_GIF){
		header("Content-Type: image/gif");
		imagegif($im);
	}elseif(imagetypes() & IMG_WBMP){
		header("Content-Type: image/vnd.wap.wbmp");
		imagewbmp($im);
	}else{
		die("不支持图像创建!");
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值