PHP生产一个验证码图片,PHP生成图片验证码

PHP生成图片验证码

分为两个方法函数

/**

* PHP生成图片验证码

* Class VerifyImage

*/

class VerifyImage

{

// 生成随机字串

private $verifyCode;

// 图片对象

private $image;

/**

* todo:生成随机验证码

* @param int $type 类型 【1】纯数字,【2】纯字母,【3】数字加字母

* @param int $length

* @return bool|string

*/

public function createCode($type = 3, $length = 5)

{

if ($type == 1) {

$verifyCode = implode('', range(0, 9));

} elseif ($type == 2) {

$verifyCode = implode('', array_merge(range('a', 'z'), range('A', 'Z')));

} else {

$verifyCode = implode('', array_merge(range('a', 'z'), range(0, 9), range('A', 'Z')));

}

//判断生成字符是否符合要求

if (strlen($verifyCode) < $length) {

return false;

}

//打乱字符串

$verifyCode = str_shuffle($verifyCode);

$this->verifyCode = substr($verifyCode, 0, $length);

return $this->verifyCode;

}

/**

* todo:加入字符,生成图片,并加入干扰线,干扰素

* @param int $width 图片宽度

* @param int $height 图片高度

*/

public function createImage($width = 80, $height = 30)

{

$verifyCode = $this->verifyCode;

$image = imagecreatetruecolor($width, $height);

//白色背景

$white = imagecolorallocate($image, 255, 255, 255);

//字体颜色

$fontStyle = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));;

imagefill($image, 0, 0, $white);

// 使用默认字体,无法修改文字大小

// imagestring($image, 5, 10, 10, $verifyCode, $fontStyle);

// 导入自定义字体,修改文字大小

imagettftext($image, 24, 0, 5, 20, $fontStyle, '../microsofthimalaya.ttf', $verifyCode);

//加入干扰点

for ($i = 0; $i < 80; $i++) {

$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));

imagesetpixel($image, rand(0, $width), rand(0, $height), $color);

}

//干扰线

for ($i = 0; $i < 5; $i++) {

$color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));

imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);

}

//输出图片

header("Content-type: image/png");

imagepng($image);

//释放资源

imagedestroy($image);

}

}

?>

实例

$VerifyImage = new VerifyImage();

$code = $VerifyImage->createCode();

$_SESSION['$VerifyCode'] = $code;

$VerifyImage->createImage();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值