前言
一般情况下我们在做程序的时候肯定会有很多地方使用到随机字符串、比如做验证码用到的、然后就把这个函数封装起来、原理是随机抓取字符串、对字符串进行拼接
本方法可以输出三种类型验证码:分别为纯数字(0)、纯字母(1)、数字和字母(3)。
1、验证码类初始化
class Code{
//验证码个数
protected $number;
//验证码类型
protected $codeType;
//图像宽度
protected $width;
//图像高度
protected $height;
//图片资源
protected $image;
//验证码字符串
protected $code;
public function __construct($number,$codeType,$width,$height){
//初始化属性
$this->number=$number;
$this->codeType=$codeType;
$this->width=$width;
$this->height=$height;
//生成验证码函数
$this->code=$this->createCode();
echo $this->code;
}
2、生成验证码字符串
protected function createCode(){
//通过验证码类型,生成不同类型验证码
switch ($this->codeType) {
case 0://纯数字
$code=$this->getNumnerCode();
break;
case 1://纯字母
$code=$this->getCharCode();
break;
case 2://数字字幕组合:
$code=$this->getNumCharCode();
break;
default:
die('不支持这种验证码类型');
}
return $code;
}
protected function getNumnerCode(){
$str=join('',range(0, 9));
return substr(str_shuffle($str), 0,$this->number);
}
protected function getCharCode(){
$str=join('',range('a', 'z'));
$str=$str.strtoupper($str);
return substr(str_shuffle($str),0, $this->number);
}
protected function getNumCharCode(){
$strNum=join('',range(0, 9));
$strCHar=join('',range('a', 'z'));
$str=$strNum.strtoupper($strCHar);
return substr(str_shuffle($str),0, $this->number);
}
3、完整代码
<?php
$code=new Code(4,0,100,50);
class Code{
//验证码个数
protected $number;
//验证码类型
protected $codeType;
//图像宽度
protected $width;
//图像高度
protected $height;
//图片资源
protected $image;
//验证码字符串
protected $code;
public function __construct($number,$codeType,$width,$height){
//初始化属性
$this->number=$number;
$this->codeType=$codeType;
$this->width=$width;
$this->height=$height;
//生成验证码函数
$this->code=$this->createCode();
echo $this->code;
}
protected function createCode(){
//通过验证码类型,生成不同类型验证码
switch ($this->codeType) {
case 0://纯数字
$code=$this->getNumnerCode();
break;
case 1://纯字母
$code=$this->getCharCode();
break;
case 2://数字字幕组合:
$code=$this->getNumCharCode();
break;
default:
die('不支持这种验证码类型');
}
return $code;
}
protected function getNumnerCode(){
$str=join('',range(0, 9));
return substr(str_shuffle($str), 0,$this->number);
}
protected function getCharCode(){
$str=join('',range('a', 'z'));
$str=$str.strtoupper($str);
return substr(str_shuffle($str),0, $this->number);
}
protected function getNumCharCode(){
$strNum=join('',range(0, 9));
$strCHar=join('',range('a', 'z'));
$str=$strNum.strtoupper($strCHar);
return substr(str_shuffle($str),0, $this->number);
}
}
4、注意事项
$code=new Code(4,0,100,50);
new的时候必须有这几个参数,否则可能会出现错误
注:$code=new Code(4,0,100,50);中4代表验证码长度,0 代表验证码类型(纯数字类型),100代表宽度,50代表长度。
下一篇我们将会做输出验证码图像。有需要的可以关注我的博客。