Home > Backend Development > PHP Tutorial > php verification code encapsulation class

php verification code encapsulation class

亚连
Release: 2023-03-26 08:36:01
Original
2159 people have browsed it

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template