Home  >  Article  >  Backend Development  >  php verification code encapsulation class

php verification code encapsulation class

亚连
亚连Original
2018-05-17 10:42:182151browse

The following is the php Verification code encapsulation class I compiled. If you are interested, you may wish to take a look

<?php  
/**  
*验证码封装类  
*/  
class CaptchaLib {  
private $length;  
//验证码长度  
private $font=5;  
//内置字体大小  1,2,3,4,5  
//通过构造函数赋值  
public function construct($length=4,$font=5) {  
$this->length=$length;  
$this->font=$font;  
}  
//生成随机字符串  
private function generalCode() {  
$char_array=array_merge(range(&#39;A&#39;,&#39;Z&#39;),range(&#39;a&#39;,&#39;z&#39;),range(0,9));//生成一个字母和数字的数组  
$index=array_rand($char_array,$this->length);  
//随机取4个字符,返回的是字符下标  
shuffle($index);  
//打乱下标  
//拼接字符串  
$str=&#39;&#39;;  
foreach($index as $i) {  
$str.=$char_array[$i];  
}  
return $str;  
}  
//生成验证码  
public function generalCaptcha() {  
$str=$this->generalCode();  
//打开背景图  
$bg_path=&#39;./captcha/captcha_bg&#39;.rand(1,5).&#39;.jpg&#39;;  
//背景图地址 5张随机背景图片  
$img=imagecreatefromjpeg($bg_path);  
//打开图片  
//定义前景色  
$color=imagecolorallocate($img,0,0,0);  
if(rand(1,2)==2)  
$color=imagecolorallocate($img,255,255,255);  
//将字符串写到图片上  
$x=(imagesx($img)-imagefontwidth($this->font)*strlen($str))/2;  
$y=(imagesy($img)-imagefontheight($this->font))/2;  
imagestring($img,$this->font,$x,$y,$str,$color);  
header(&#39;content-type:image/png&#39;);  
imagepng($img);  
imagedestroy($img);  
}  
}  
//测试  
$captcha=new CaptchaLib(8,4);  
$captcha->generalCaptcha();

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Key points analysis and answers to rewriting and polymorphism

How to rewrite the padleft method in js

What are the inheritance methods in js

The above is the detailed content of php verification code encapsulation class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn